]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - fs/btrfs/inode.c
btrfs: make orphan cleanup less verbose
[mirror_ubuntu-bionic-kernel.git] / fs / btrfs / inode.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/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include <linux/mount.h>
42 #include <linux/btrfs.h>
43 #include <linux/blkdev.h>
44 #include "compat.h"
45 #include "ctree.h"
46 #include "disk-io.h"
47 #include "transaction.h"
48 #include "btrfs_inode.h"
49 #include "print-tree.h"
50 #include "ordered-data.h"
51 #include "xattr.h"
52 #include "tree-log.h"
53 #include "volumes.h"
54 #include "compression.h"
55 #include "locking.h"
56 #include "free-space-cache.h"
57 #include "inode-map.h"
58 #include "backref.h"
59
60 struct btrfs_iget_args {
61 u64 ino;
62 struct btrfs_root *root;
63 };
64
65 static const struct inode_operations btrfs_dir_inode_operations;
66 static const struct inode_operations btrfs_symlink_inode_operations;
67 static const struct inode_operations btrfs_dir_ro_inode_operations;
68 static const struct inode_operations btrfs_special_inode_operations;
69 static const struct inode_operations btrfs_file_inode_operations;
70 static const struct address_space_operations btrfs_aops;
71 static const struct address_space_operations btrfs_symlink_aops;
72 static const struct file_operations btrfs_dir_file_operations;
73 static struct extent_io_ops btrfs_extent_io_ops;
74
75 static struct kmem_cache *btrfs_inode_cachep;
76 static struct kmem_cache *btrfs_delalloc_work_cachep;
77 struct kmem_cache *btrfs_trans_handle_cachep;
78 struct kmem_cache *btrfs_transaction_cachep;
79 struct kmem_cache *btrfs_path_cachep;
80 struct kmem_cache *btrfs_free_space_cachep;
81
82 #define S_SHIFT 12
83 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
84 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
85 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
86 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
87 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
88 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
89 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
90 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
91 };
92
93 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
94 static int btrfs_truncate(struct inode *inode);
95 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
96 static noinline int cow_file_range(struct inode *inode,
97 struct page *locked_page,
98 u64 start, u64 end, int *page_started,
99 unsigned long *nr_written, int unlock);
100 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
101 u64 len, u64 orig_start,
102 u64 block_start, u64 block_len,
103 u64 orig_block_len, int type);
104
105 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
106 struct inode *inode, struct inode *dir,
107 const struct qstr *qstr)
108 {
109 int err;
110
111 err = btrfs_init_acl(trans, inode, dir);
112 if (!err)
113 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
114 return err;
115 }
116
117 /*
118 * this does all the hard work for inserting an inline extent into
119 * the btree. The caller should have done a btrfs_drop_extents so that
120 * no overlapping inline items exist in the btree
121 */
122 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
123 struct btrfs_root *root, struct inode *inode,
124 u64 start, size_t size, size_t compressed_size,
125 int compress_type,
126 struct page **compressed_pages)
127 {
128 struct btrfs_key key;
129 struct btrfs_path *path;
130 struct extent_buffer *leaf;
131 struct page *page = NULL;
132 char *kaddr;
133 unsigned long ptr;
134 struct btrfs_file_extent_item *ei;
135 int err = 0;
136 int ret;
137 size_t cur_size = size;
138 size_t datasize;
139 unsigned long offset;
140
141 if (compressed_size && compressed_pages)
142 cur_size = compressed_size;
143
144 path = btrfs_alloc_path();
145 if (!path)
146 return -ENOMEM;
147
148 path->leave_spinning = 1;
149
150 key.objectid = btrfs_ino(inode);
151 key.offset = start;
152 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
153 datasize = btrfs_file_extent_calc_inline_size(cur_size);
154
155 inode_add_bytes(inode, size);
156 ret = btrfs_insert_empty_item(trans, root, path, &key,
157 datasize);
158 if (ret) {
159 err = ret;
160 goto fail;
161 }
162 leaf = path->nodes[0];
163 ei = btrfs_item_ptr(leaf, path->slots[0],
164 struct btrfs_file_extent_item);
165 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
166 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
167 btrfs_set_file_extent_encryption(leaf, ei, 0);
168 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
169 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
170 ptr = btrfs_file_extent_inline_start(ei);
171
172 if (compress_type != BTRFS_COMPRESS_NONE) {
173 struct page *cpage;
174 int i = 0;
175 while (compressed_size > 0) {
176 cpage = compressed_pages[i];
177 cur_size = min_t(unsigned long, compressed_size,
178 PAGE_CACHE_SIZE);
179
180 kaddr = kmap_atomic(cpage);
181 write_extent_buffer(leaf, kaddr, ptr, cur_size);
182 kunmap_atomic(kaddr);
183
184 i++;
185 ptr += cur_size;
186 compressed_size -= cur_size;
187 }
188 btrfs_set_file_extent_compression(leaf, ei,
189 compress_type);
190 } else {
191 page = find_get_page(inode->i_mapping,
192 start >> PAGE_CACHE_SHIFT);
193 btrfs_set_file_extent_compression(leaf, ei, 0);
194 kaddr = kmap_atomic(page);
195 offset = start & (PAGE_CACHE_SIZE - 1);
196 write_extent_buffer(leaf, kaddr + offset, ptr, size);
197 kunmap_atomic(kaddr);
198 page_cache_release(page);
199 }
200 btrfs_mark_buffer_dirty(leaf);
201 btrfs_free_path(path);
202
203 /*
204 * we're an inline extent, so nobody can
205 * extend the file past i_size without locking
206 * a page we already have locked.
207 *
208 * We must do any isize and inode updates
209 * before we unlock the pages. Otherwise we
210 * could end up racing with unlink.
211 */
212 BTRFS_I(inode)->disk_i_size = inode->i_size;
213 ret = btrfs_update_inode(trans, root, inode);
214
215 return ret;
216 fail:
217 btrfs_free_path(path);
218 return err;
219 }
220
221
222 /*
223 * conditionally insert an inline extent into the file. This
224 * does the checks required to make sure the data is small enough
225 * to fit as an inline extent.
226 */
227 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
228 struct btrfs_root *root,
229 struct inode *inode, u64 start, u64 end,
230 size_t compressed_size, int compress_type,
231 struct page **compressed_pages)
232 {
233 u64 isize = i_size_read(inode);
234 u64 actual_end = min(end + 1, isize);
235 u64 inline_len = actual_end - start;
236 u64 aligned_end = ALIGN(end, root->sectorsize);
237 u64 data_len = inline_len;
238 int ret;
239
240 if (compressed_size)
241 data_len = compressed_size;
242
243 if (start > 0 ||
244 actual_end >= PAGE_CACHE_SIZE ||
245 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
246 (!compressed_size &&
247 (actual_end & (root->sectorsize - 1)) == 0) ||
248 end + 1 < isize ||
249 data_len > root->fs_info->max_inline) {
250 return 1;
251 }
252
253 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
254 if (ret)
255 return ret;
256
257 if (isize > actual_end)
258 inline_len = min_t(u64, isize, actual_end);
259 ret = insert_inline_extent(trans, root, inode, start,
260 inline_len, compressed_size,
261 compress_type, compressed_pages);
262 if (ret && ret != -ENOSPC) {
263 btrfs_abort_transaction(trans, root, ret);
264 return ret;
265 } else if (ret == -ENOSPC) {
266 return 1;
267 }
268
269 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
270 btrfs_delalloc_release_metadata(inode, end + 1 - start);
271 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
272 return 0;
273 }
274
275 struct async_extent {
276 u64 start;
277 u64 ram_size;
278 u64 compressed_size;
279 struct page **pages;
280 unsigned long nr_pages;
281 int compress_type;
282 struct list_head list;
283 };
284
285 struct async_cow {
286 struct inode *inode;
287 struct btrfs_root *root;
288 struct page *locked_page;
289 u64 start;
290 u64 end;
291 struct list_head extents;
292 struct btrfs_work work;
293 };
294
295 static noinline int add_async_extent(struct async_cow *cow,
296 u64 start, u64 ram_size,
297 u64 compressed_size,
298 struct page **pages,
299 unsigned long nr_pages,
300 int compress_type)
301 {
302 struct async_extent *async_extent;
303
304 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
305 BUG_ON(!async_extent); /* -ENOMEM */
306 async_extent->start = start;
307 async_extent->ram_size = ram_size;
308 async_extent->compressed_size = compressed_size;
309 async_extent->pages = pages;
310 async_extent->nr_pages = nr_pages;
311 async_extent->compress_type = compress_type;
312 list_add_tail(&async_extent->list, &cow->extents);
313 return 0;
314 }
315
316 /*
317 * we create compressed extents in two phases. The first
318 * phase compresses a range of pages that have already been
319 * locked (both pages and state bits are locked).
320 *
321 * This is done inside an ordered work queue, and the compression
322 * is spread across many cpus. The actual IO submission is step
323 * two, and the ordered work queue takes care of making sure that
324 * happens in the same order things were put onto the queue by
325 * writepages and friends.
326 *
327 * If this code finds it can't get good compression, it puts an
328 * entry onto the work queue to write the uncompressed bytes. This
329 * makes sure that both compressed inodes and uncompressed inodes
330 * are written in the same order that the flusher thread sent them
331 * down.
332 */
333 static noinline int compress_file_range(struct inode *inode,
334 struct page *locked_page,
335 u64 start, u64 end,
336 struct async_cow *async_cow,
337 int *num_added)
338 {
339 struct btrfs_root *root = BTRFS_I(inode)->root;
340 struct btrfs_trans_handle *trans;
341 u64 num_bytes;
342 u64 blocksize = root->sectorsize;
343 u64 actual_end;
344 u64 isize = i_size_read(inode);
345 int ret = 0;
346 struct page **pages = NULL;
347 unsigned long nr_pages;
348 unsigned long nr_pages_ret = 0;
349 unsigned long total_compressed = 0;
350 unsigned long total_in = 0;
351 unsigned long max_compressed = 128 * 1024;
352 unsigned long max_uncompressed = 128 * 1024;
353 int i;
354 int will_compress;
355 int compress_type = root->fs_info->compress_type;
356 int redirty = 0;
357
358 /* if this is a small write inside eof, kick off a defrag */
359 if ((end - start + 1) < 16 * 1024 &&
360 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
361 btrfs_add_inode_defrag(NULL, inode);
362
363 actual_end = min_t(u64, isize, end + 1);
364 again:
365 will_compress = 0;
366 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
367 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
368
369 /*
370 * we don't want to send crud past the end of i_size through
371 * compression, that's just a waste of CPU time. So, if the
372 * end of the file is before the start of our current
373 * requested range of bytes, we bail out to the uncompressed
374 * cleanup code that can deal with all of this.
375 *
376 * It isn't really the fastest way to fix things, but this is a
377 * very uncommon corner.
378 */
379 if (actual_end <= start)
380 goto cleanup_and_bail_uncompressed;
381
382 total_compressed = actual_end - start;
383
384 /* we want to make sure that amount of ram required to uncompress
385 * an extent is reasonable, so we limit the total size in ram
386 * of a compressed extent to 128k. This is a crucial number
387 * because it also controls how easily we can spread reads across
388 * cpus for decompression.
389 *
390 * We also want to make sure the amount of IO required to do
391 * a random read is reasonably small, so we limit the size of
392 * a compressed extent to 128k.
393 */
394 total_compressed = min(total_compressed, max_uncompressed);
395 num_bytes = ALIGN(end - start + 1, blocksize);
396 num_bytes = max(blocksize, num_bytes);
397 total_in = 0;
398 ret = 0;
399
400 /*
401 * we do compression for mount -o compress and when the
402 * inode has not been flagged as nocompress. This flag can
403 * change at any time if we discover bad compression ratios.
404 */
405 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
406 (btrfs_test_opt(root, COMPRESS) ||
407 (BTRFS_I(inode)->force_compress) ||
408 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
409 WARN_ON(pages);
410 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
411 if (!pages) {
412 /* just bail out to the uncompressed code */
413 goto cont;
414 }
415
416 if (BTRFS_I(inode)->force_compress)
417 compress_type = BTRFS_I(inode)->force_compress;
418
419 /*
420 * we need to call clear_page_dirty_for_io on each
421 * page in the range. Otherwise applications with the file
422 * mmap'd can wander in and change the page contents while
423 * we are compressing them.
424 *
425 * If the compression fails for any reason, we set the pages
426 * dirty again later on.
427 */
428 extent_range_clear_dirty_for_io(inode, start, end);
429 redirty = 1;
430 ret = btrfs_compress_pages(compress_type,
431 inode->i_mapping, start,
432 total_compressed, pages,
433 nr_pages, &nr_pages_ret,
434 &total_in,
435 &total_compressed,
436 max_compressed);
437
438 if (!ret) {
439 unsigned long offset = total_compressed &
440 (PAGE_CACHE_SIZE - 1);
441 struct page *page = pages[nr_pages_ret - 1];
442 char *kaddr;
443
444 /* zero the tail end of the last page, we might be
445 * sending it down to disk
446 */
447 if (offset) {
448 kaddr = kmap_atomic(page);
449 memset(kaddr + offset, 0,
450 PAGE_CACHE_SIZE - offset);
451 kunmap_atomic(kaddr);
452 }
453 will_compress = 1;
454 }
455 }
456 cont:
457 if (start == 0) {
458 trans = btrfs_join_transaction(root);
459 if (IS_ERR(trans)) {
460 ret = PTR_ERR(trans);
461 trans = NULL;
462 goto cleanup_and_out;
463 }
464 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
465
466 /* lets try to make an inline extent */
467 if (ret || total_in < (actual_end - start)) {
468 /* we didn't compress the entire range, try
469 * to make an uncompressed inline extent.
470 */
471 ret = cow_file_range_inline(trans, root, inode,
472 start, end, 0, 0, NULL);
473 } else {
474 /* try making a compressed inline extent */
475 ret = cow_file_range_inline(trans, root, inode,
476 start, end,
477 total_compressed,
478 compress_type, pages);
479 }
480 if (ret <= 0) {
481 /*
482 * inline extent creation worked or returned error,
483 * we don't need to create any more async work items.
484 * Unlock and free up our temp pages.
485 */
486 extent_clear_unlock_delalloc(inode,
487 &BTRFS_I(inode)->io_tree,
488 start, end, NULL,
489 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
490 EXTENT_CLEAR_DELALLOC |
491 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
492
493 btrfs_end_transaction(trans, root);
494 goto free_pages_out;
495 }
496 btrfs_end_transaction(trans, root);
497 }
498
499 if (will_compress) {
500 /*
501 * we aren't doing an inline extent round the compressed size
502 * up to a block size boundary so the allocator does sane
503 * things
504 */
505 total_compressed = ALIGN(total_compressed, blocksize);
506
507 /*
508 * one last check to make sure the compression is really a
509 * win, compare the page count read with the blocks on disk
510 */
511 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
512 if (total_compressed >= total_in) {
513 will_compress = 0;
514 } else {
515 num_bytes = total_in;
516 }
517 }
518 if (!will_compress && pages) {
519 /*
520 * the compression code ran but failed to make things smaller,
521 * free any pages it allocated and our page pointer array
522 */
523 for (i = 0; i < nr_pages_ret; i++) {
524 WARN_ON(pages[i]->mapping);
525 page_cache_release(pages[i]);
526 }
527 kfree(pages);
528 pages = NULL;
529 total_compressed = 0;
530 nr_pages_ret = 0;
531
532 /* flag the file so we don't compress in the future */
533 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
534 !(BTRFS_I(inode)->force_compress)) {
535 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
536 }
537 }
538 if (will_compress) {
539 *num_added += 1;
540
541 /* the async work queues will take care of doing actual
542 * allocation on disk for these compressed pages,
543 * and will submit them to the elevator.
544 */
545 add_async_extent(async_cow, start, num_bytes,
546 total_compressed, pages, nr_pages_ret,
547 compress_type);
548
549 if (start + num_bytes < end) {
550 start += num_bytes;
551 pages = NULL;
552 cond_resched();
553 goto again;
554 }
555 } else {
556 cleanup_and_bail_uncompressed:
557 /*
558 * No compression, but we still need to write the pages in
559 * the file we've been given so far. redirty the locked
560 * page if it corresponds to our extent and set things up
561 * for the async work queue to run cow_file_range to do
562 * the normal delalloc dance
563 */
564 if (page_offset(locked_page) >= start &&
565 page_offset(locked_page) <= end) {
566 __set_page_dirty_nobuffers(locked_page);
567 /* unlocked later on in the async handlers */
568 }
569 if (redirty)
570 extent_range_redirty_for_io(inode, start, end);
571 add_async_extent(async_cow, start, end - start + 1,
572 0, NULL, 0, BTRFS_COMPRESS_NONE);
573 *num_added += 1;
574 }
575
576 out:
577 return ret;
578
579 free_pages_out:
580 for (i = 0; i < nr_pages_ret; i++) {
581 WARN_ON(pages[i]->mapping);
582 page_cache_release(pages[i]);
583 }
584 kfree(pages);
585
586 goto out;
587
588 cleanup_and_out:
589 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
590 start, end, NULL,
591 EXTENT_CLEAR_UNLOCK_PAGE |
592 EXTENT_CLEAR_DIRTY |
593 EXTENT_CLEAR_DELALLOC |
594 EXTENT_SET_WRITEBACK |
595 EXTENT_END_WRITEBACK);
596 if (!trans || IS_ERR(trans))
597 btrfs_error(root->fs_info, ret, "Failed to join transaction");
598 else
599 btrfs_abort_transaction(trans, root, ret);
600 goto free_pages_out;
601 }
602
603 /*
604 * phase two of compressed writeback. This is the ordered portion
605 * of the code, which only gets called in the order the work was
606 * queued. We walk all the async extents created by compress_file_range
607 * and send them down to the disk.
608 */
609 static noinline int submit_compressed_extents(struct inode *inode,
610 struct async_cow *async_cow)
611 {
612 struct async_extent *async_extent;
613 u64 alloc_hint = 0;
614 struct btrfs_trans_handle *trans;
615 struct btrfs_key ins;
616 struct extent_map *em;
617 struct btrfs_root *root = BTRFS_I(inode)->root;
618 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
619 struct extent_io_tree *io_tree;
620 int ret = 0;
621
622 if (list_empty(&async_cow->extents))
623 return 0;
624
625 again:
626 while (!list_empty(&async_cow->extents)) {
627 async_extent = list_entry(async_cow->extents.next,
628 struct async_extent, list);
629 list_del(&async_extent->list);
630
631 io_tree = &BTRFS_I(inode)->io_tree;
632
633 retry:
634 /* did the compression code fall back to uncompressed IO? */
635 if (!async_extent->pages) {
636 int page_started = 0;
637 unsigned long nr_written = 0;
638
639 lock_extent(io_tree, async_extent->start,
640 async_extent->start +
641 async_extent->ram_size - 1);
642
643 /* allocate blocks */
644 ret = cow_file_range(inode, async_cow->locked_page,
645 async_extent->start,
646 async_extent->start +
647 async_extent->ram_size - 1,
648 &page_started, &nr_written, 0);
649
650 /* JDM XXX */
651
652 /*
653 * if page_started, cow_file_range inserted an
654 * inline extent and took care of all the unlocking
655 * and IO for us. Otherwise, we need to submit
656 * all those pages down to the drive.
657 */
658 if (!page_started && !ret)
659 extent_write_locked_range(io_tree,
660 inode, async_extent->start,
661 async_extent->start +
662 async_extent->ram_size - 1,
663 btrfs_get_extent,
664 WB_SYNC_ALL);
665 else if (ret)
666 unlock_page(async_cow->locked_page);
667 kfree(async_extent);
668 cond_resched();
669 continue;
670 }
671
672 lock_extent(io_tree, async_extent->start,
673 async_extent->start + async_extent->ram_size - 1);
674
675 trans = btrfs_join_transaction(root);
676 if (IS_ERR(trans)) {
677 ret = PTR_ERR(trans);
678 } else {
679 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
680 ret = btrfs_reserve_extent(trans, root,
681 async_extent->compressed_size,
682 async_extent->compressed_size,
683 0, alloc_hint, &ins, 1);
684 if (ret && ret != -ENOSPC)
685 btrfs_abort_transaction(trans, root, ret);
686 btrfs_end_transaction(trans, root);
687 }
688
689 if (ret) {
690 int i;
691
692 for (i = 0; i < async_extent->nr_pages; i++) {
693 WARN_ON(async_extent->pages[i]->mapping);
694 page_cache_release(async_extent->pages[i]);
695 }
696 kfree(async_extent->pages);
697 async_extent->nr_pages = 0;
698 async_extent->pages = NULL;
699
700 if (ret == -ENOSPC)
701 goto retry;
702 goto out_free;
703 }
704
705 /*
706 * here we're doing allocation and writeback of the
707 * compressed pages
708 */
709 btrfs_drop_extent_cache(inode, async_extent->start,
710 async_extent->start +
711 async_extent->ram_size - 1, 0);
712
713 em = alloc_extent_map();
714 if (!em)
715 goto out_free_reserve;
716 em->start = async_extent->start;
717 em->len = async_extent->ram_size;
718 em->orig_start = em->start;
719 em->mod_start = em->start;
720 em->mod_len = em->len;
721
722 em->block_start = ins.objectid;
723 em->block_len = ins.offset;
724 em->orig_block_len = ins.offset;
725 em->bdev = root->fs_info->fs_devices->latest_bdev;
726 em->compress_type = async_extent->compress_type;
727 set_bit(EXTENT_FLAG_PINNED, &em->flags);
728 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
729 em->generation = -1;
730
731 while (1) {
732 write_lock(&em_tree->lock);
733 ret = add_extent_mapping(em_tree, em);
734 if (!ret)
735 list_move(&em->list,
736 &em_tree->modified_extents);
737 write_unlock(&em_tree->lock);
738 if (ret != -EEXIST) {
739 free_extent_map(em);
740 break;
741 }
742 btrfs_drop_extent_cache(inode, async_extent->start,
743 async_extent->start +
744 async_extent->ram_size - 1, 0);
745 }
746
747 if (ret)
748 goto out_free_reserve;
749
750 ret = btrfs_add_ordered_extent_compress(inode,
751 async_extent->start,
752 ins.objectid,
753 async_extent->ram_size,
754 ins.offset,
755 BTRFS_ORDERED_COMPRESSED,
756 async_extent->compress_type);
757 if (ret)
758 goto out_free_reserve;
759
760 /*
761 * clear dirty, set writeback and unlock the pages.
762 */
763 extent_clear_unlock_delalloc(inode,
764 &BTRFS_I(inode)->io_tree,
765 async_extent->start,
766 async_extent->start +
767 async_extent->ram_size - 1,
768 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
769 EXTENT_CLEAR_UNLOCK |
770 EXTENT_CLEAR_DELALLOC |
771 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
772
773 ret = btrfs_submit_compressed_write(inode,
774 async_extent->start,
775 async_extent->ram_size,
776 ins.objectid,
777 ins.offset, async_extent->pages,
778 async_extent->nr_pages);
779 alloc_hint = ins.objectid + ins.offset;
780 kfree(async_extent);
781 if (ret)
782 goto out;
783 cond_resched();
784 }
785 ret = 0;
786 out:
787 return ret;
788 out_free_reserve:
789 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
790 out_free:
791 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
792 async_extent->start,
793 async_extent->start +
794 async_extent->ram_size - 1,
795 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
796 EXTENT_CLEAR_UNLOCK |
797 EXTENT_CLEAR_DELALLOC |
798 EXTENT_CLEAR_DIRTY |
799 EXTENT_SET_WRITEBACK |
800 EXTENT_END_WRITEBACK);
801 kfree(async_extent);
802 goto again;
803 }
804
805 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
806 u64 num_bytes)
807 {
808 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
809 struct extent_map *em;
810 u64 alloc_hint = 0;
811
812 read_lock(&em_tree->lock);
813 em = search_extent_mapping(em_tree, start, num_bytes);
814 if (em) {
815 /*
816 * if block start isn't an actual block number then find the
817 * first block in this inode and use that as a hint. If that
818 * block is also bogus then just don't worry about it.
819 */
820 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
821 free_extent_map(em);
822 em = search_extent_mapping(em_tree, 0, 0);
823 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
824 alloc_hint = em->block_start;
825 if (em)
826 free_extent_map(em);
827 } else {
828 alloc_hint = em->block_start;
829 free_extent_map(em);
830 }
831 }
832 read_unlock(&em_tree->lock);
833
834 return alloc_hint;
835 }
836
837 /*
838 * when extent_io.c finds a delayed allocation range in the file,
839 * the call backs end up in this code. The basic idea is to
840 * allocate extents on disk for the range, and create ordered data structs
841 * in ram to track those extents.
842 *
843 * locked_page is the page that writepage had locked already. We use
844 * it to make sure we don't do extra locks or unlocks.
845 *
846 * *page_started is set to one if we unlock locked_page and do everything
847 * required to start IO on it. It may be clean and already done with
848 * IO when we return.
849 */
850 static noinline int __cow_file_range(struct btrfs_trans_handle *trans,
851 struct inode *inode,
852 struct btrfs_root *root,
853 struct page *locked_page,
854 u64 start, u64 end, int *page_started,
855 unsigned long *nr_written,
856 int unlock)
857 {
858 u64 alloc_hint = 0;
859 u64 num_bytes;
860 unsigned long ram_size;
861 u64 disk_num_bytes;
862 u64 cur_alloc_size;
863 u64 blocksize = root->sectorsize;
864 struct btrfs_key ins;
865 struct extent_map *em;
866 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
867 int ret = 0;
868
869 BUG_ON(btrfs_is_free_space_inode(inode));
870
871 num_bytes = ALIGN(end - start + 1, blocksize);
872 num_bytes = max(blocksize, num_bytes);
873 disk_num_bytes = num_bytes;
874
875 /* if this is a small write inside eof, kick off defrag */
876 if (num_bytes < 64 * 1024 &&
877 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
878 btrfs_add_inode_defrag(trans, inode);
879
880 if (start == 0) {
881 /* lets try to make an inline extent */
882 ret = cow_file_range_inline(trans, root, inode,
883 start, end, 0, 0, NULL);
884 if (ret == 0) {
885 extent_clear_unlock_delalloc(inode,
886 &BTRFS_I(inode)->io_tree,
887 start, end, NULL,
888 EXTENT_CLEAR_UNLOCK_PAGE |
889 EXTENT_CLEAR_UNLOCK |
890 EXTENT_CLEAR_DELALLOC |
891 EXTENT_CLEAR_DIRTY |
892 EXTENT_SET_WRITEBACK |
893 EXTENT_END_WRITEBACK);
894
895 *nr_written = *nr_written +
896 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
897 *page_started = 1;
898 goto out;
899 } else if (ret < 0) {
900 btrfs_abort_transaction(trans, root, ret);
901 goto out_unlock;
902 }
903 }
904
905 BUG_ON(disk_num_bytes >
906 btrfs_super_total_bytes(root->fs_info->super_copy));
907
908 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
909 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
910
911 while (disk_num_bytes > 0) {
912 unsigned long op;
913
914 cur_alloc_size = disk_num_bytes;
915 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
916 root->sectorsize, 0, alloc_hint,
917 &ins, 1);
918 if (ret < 0) {
919 btrfs_abort_transaction(trans, root, ret);
920 goto out_unlock;
921 }
922
923 em = alloc_extent_map();
924 BUG_ON(!em); /* -ENOMEM */
925 em->start = start;
926 em->orig_start = em->start;
927 ram_size = ins.offset;
928 em->len = ins.offset;
929 em->mod_start = em->start;
930 em->mod_len = em->len;
931
932 em->block_start = ins.objectid;
933 em->block_len = ins.offset;
934 em->orig_block_len = ins.offset;
935 em->bdev = root->fs_info->fs_devices->latest_bdev;
936 set_bit(EXTENT_FLAG_PINNED, &em->flags);
937 em->generation = -1;
938
939 while (1) {
940 write_lock(&em_tree->lock);
941 ret = add_extent_mapping(em_tree, em);
942 if (!ret)
943 list_move(&em->list,
944 &em_tree->modified_extents);
945 write_unlock(&em_tree->lock);
946 if (ret != -EEXIST) {
947 free_extent_map(em);
948 break;
949 }
950 btrfs_drop_extent_cache(inode, start,
951 start + ram_size - 1, 0);
952 }
953
954 cur_alloc_size = ins.offset;
955 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
956 ram_size, cur_alloc_size, 0);
957 BUG_ON(ret); /* -ENOMEM */
958
959 if (root->root_key.objectid ==
960 BTRFS_DATA_RELOC_TREE_OBJECTID) {
961 ret = btrfs_reloc_clone_csums(inode, start,
962 cur_alloc_size);
963 if (ret) {
964 btrfs_abort_transaction(trans, root, ret);
965 goto out_unlock;
966 }
967 }
968
969 if (disk_num_bytes < cur_alloc_size)
970 break;
971
972 /* we're not doing compressed IO, don't unlock the first
973 * page (which the caller expects to stay locked), don't
974 * clear any dirty bits and don't set any writeback bits
975 *
976 * Do set the Private2 bit so we know this page was properly
977 * setup for writepage
978 */
979 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
980 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
981 EXTENT_SET_PRIVATE2;
982
983 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
984 start, start + ram_size - 1,
985 locked_page, op);
986 disk_num_bytes -= cur_alloc_size;
987 num_bytes -= cur_alloc_size;
988 alloc_hint = ins.objectid + ins.offset;
989 start += cur_alloc_size;
990 }
991 out:
992 return ret;
993
994 out_unlock:
995 extent_clear_unlock_delalloc(inode,
996 &BTRFS_I(inode)->io_tree,
997 start, end, locked_page,
998 EXTENT_CLEAR_UNLOCK_PAGE |
999 EXTENT_CLEAR_UNLOCK |
1000 EXTENT_CLEAR_DELALLOC |
1001 EXTENT_CLEAR_DIRTY |
1002 EXTENT_SET_WRITEBACK |
1003 EXTENT_END_WRITEBACK);
1004
1005 goto out;
1006 }
1007
1008 static noinline int cow_file_range(struct inode *inode,
1009 struct page *locked_page,
1010 u64 start, u64 end, int *page_started,
1011 unsigned long *nr_written,
1012 int unlock)
1013 {
1014 struct btrfs_trans_handle *trans;
1015 struct btrfs_root *root = BTRFS_I(inode)->root;
1016 int ret;
1017
1018 trans = btrfs_join_transaction(root);
1019 if (IS_ERR(trans)) {
1020 extent_clear_unlock_delalloc(inode,
1021 &BTRFS_I(inode)->io_tree,
1022 start, end, locked_page,
1023 EXTENT_CLEAR_UNLOCK_PAGE |
1024 EXTENT_CLEAR_UNLOCK |
1025 EXTENT_CLEAR_DELALLOC |
1026 EXTENT_CLEAR_DIRTY |
1027 EXTENT_SET_WRITEBACK |
1028 EXTENT_END_WRITEBACK);
1029 return PTR_ERR(trans);
1030 }
1031 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1032
1033 ret = __cow_file_range(trans, inode, root, locked_page, start, end,
1034 page_started, nr_written, unlock);
1035
1036 btrfs_end_transaction(trans, root);
1037
1038 return ret;
1039 }
1040
1041 /*
1042 * work queue call back to started compression on a file and pages
1043 */
1044 static noinline void async_cow_start(struct btrfs_work *work)
1045 {
1046 struct async_cow *async_cow;
1047 int num_added = 0;
1048 async_cow = container_of(work, struct async_cow, work);
1049
1050 compress_file_range(async_cow->inode, async_cow->locked_page,
1051 async_cow->start, async_cow->end, async_cow,
1052 &num_added);
1053 if (num_added == 0) {
1054 btrfs_add_delayed_iput(async_cow->inode);
1055 async_cow->inode = NULL;
1056 }
1057 }
1058
1059 /*
1060 * work queue call back to submit previously compressed pages
1061 */
1062 static noinline void async_cow_submit(struct btrfs_work *work)
1063 {
1064 struct async_cow *async_cow;
1065 struct btrfs_root *root;
1066 unsigned long nr_pages;
1067
1068 async_cow = container_of(work, struct async_cow, work);
1069
1070 root = async_cow->root;
1071 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1072 PAGE_CACHE_SHIFT;
1073
1074 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1075 5 * 1024 * 1024 &&
1076 waitqueue_active(&root->fs_info->async_submit_wait))
1077 wake_up(&root->fs_info->async_submit_wait);
1078
1079 if (async_cow->inode)
1080 submit_compressed_extents(async_cow->inode, async_cow);
1081 }
1082
1083 static noinline void async_cow_free(struct btrfs_work *work)
1084 {
1085 struct async_cow *async_cow;
1086 async_cow = container_of(work, struct async_cow, work);
1087 if (async_cow->inode)
1088 btrfs_add_delayed_iput(async_cow->inode);
1089 kfree(async_cow);
1090 }
1091
1092 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1093 u64 start, u64 end, int *page_started,
1094 unsigned long *nr_written)
1095 {
1096 struct async_cow *async_cow;
1097 struct btrfs_root *root = BTRFS_I(inode)->root;
1098 unsigned long nr_pages;
1099 u64 cur_end;
1100 int limit = 10 * 1024 * 1024;
1101
1102 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1103 1, 0, NULL, GFP_NOFS);
1104 while (start < end) {
1105 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1106 BUG_ON(!async_cow); /* -ENOMEM */
1107 async_cow->inode = igrab(inode);
1108 async_cow->root = root;
1109 async_cow->locked_page = locked_page;
1110 async_cow->start = start;
1111
1112 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1113 cur_end = end;
1114 else
1115 cur_end = min(end, start + 512 * 1024 - 1);
1116
1117 async_cow->end = cur_end;
1118 INIT_LIST_HEAD(&async_cow->extents);
1119
1120 async_cow->work.func = async_cow_start;
1121 async_cow->work.ordered_func = async_cow_submit;
1122 async_cow->work.ordered_free = async_cow_free;
1123 async_cow->work.flags = 0;
1124
1125 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1126 PAGE_CACHE_SHIFT;
1127 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1128
1129 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1130 &async_cow->work);
1131
1132 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1133 wait_event(root->fs_info->async_submit_wait,
1134 (atomic_read(&root->fs_info->async_delalloc_pages) <
1135 limit));
1136 }
1137
1138 while (atomic_read(&root->fs_info->async_submit_draining) &&
1139 atomic_read(&root->fs_info->async_delalloc_pages)) {
1140 wait_event(root->fs_info->async_submit_wait,
1141 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1142 0));
1143 }
1144
1145 *nr_written += nr_pages;
1146 start = cur_end + 1;
1147 }
1148 *page_started = 1;
1149 return 0;
1150 }
1151
1152 static noinline int csum_exist_in_range(struct btrfs_root *root,
1153 u64 bytenr, u64 num_bytes)
1154 {
1155 int ret;
1156 struct btrfs_ordered_sum *sums;
1157 LIST_HEAD(list);
1158
1159 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1160 bytenr + num_bytes - 1, &list, 0);
1161 if (ret == 0 && list_empty(&list))
1162 return 0;
1163
1164 while (!list_empty(&list)) {
1165 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1166 list_del(&sums->list);
1167 kfree(sums);
1168 }
1169 return 1;
1170 }
1171
1172 /*
1173 * when nowcow writeback call back. This checks for snapshots or COW copies
1174 * of the extents that exist in the file, and COWs the file as required.
1175 *
1176 * If no cow copies or snapshots exist, we write directly to the existing
1177 * blocks on disk
1178 */
1179 static noinline int run_delalloc_nocow(struct inode *inode,
1180 struct page *locked_page,
1181 u64 start, u64 end, int *page_started, int force,
1182 unsigned long *nr_written)
1183 {
1184 struct btrfs_root *root = BTRFS_I(inode)->root;
1185 struct btrfs_trans_handle *trans;
1186 struct extent_buffer *leaf;
1187 struct btrfs_path *path;
1188 struct btrfs_file_extent_item *fi;
1189 struct btrfs_key found_key;
1190 u64 cow_start;
1191 u64 cur_offset;
1192 u64 extent_end;
1193 u64 extent_offset;
1194 u64 disk_bytenr;
1195 u64 num_bytes;
1196 u64 disk_num_bytes;
1197 int extent_type;
1198 int ret, err;
1199 int type;
1200 int nocow;
1201 int check_prev = 1;
1202 bool nolock;
1203 u64 ino = btrfs_ino(inode);
1204
1205 path = btrfs_alloc_path();
1206 if (!path) {
1207 extent_clear_unlock_delalloc(inode,
1208 &BTRFS_I(inode)->io_tree,
1209 start, end, locked_page,
1210 EXTENT_CLEAR_UNLOCK_PAGE |
1211 EXTENT_CLEAR_UNLOCK |
1212 EXTENT_CLEAR_DELALLOC |
1213 EXTENT_CLEAR_DIRTY |
1214 EXTENT_SET_WRITEBACK |
1215 EXTENT_END_WRITEBACK);
1216 return -ENOMEM;
1217 }
1218
1219 nolock = btrfs_is_free_space_inode(inode);
1220
1221 if (nolock)
1222 trans = btrfs_join_transaction_nolock(root);
1223 else
1224 trans = btrfs_join_transaction(root);
1225
1226 if (IS_ERR(trans)) {
1227 extent_clear_unlock_delalloc(inode,
1228 &BTRFS_I(inode)->io_tree,
1229 start, end, locked_page,
1230 EXTENT_CLEAR_UNLOCK_PAGE |
1231 EXTENT_CLEAR_UNLOCK |
1232 EXTENT_CLEAR_DELALLOC |
1233 EXTENT_CLEAR_DIRTY |
1234 EXTENT_SET_WRITEBACK |
1235 EXTENT_END_WRITEBACK);
1236 btrfs_free_path(path);
1237 return PTR_ERR(trans);
1238 }
1239
1240 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1241
1242 cow_start = (u64)-1;
1243 cur_offset = start;
1244 while (1) {
1245 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1246 cur_offset, 0);
1247 if (ret < 0) {
1248 btrfs_abort_transaction(trans, root, ret);
1249 goto error;
1250 }
1251 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1252 leaf = path->nodes[0];
1253 btrfs_item_key_to_cpu(leaf, &found_key,
1254 path->slots[0] - 1);
1255 if (found_key.objectid == ino &&
1256 found_key.type == BTRFS_EXTENT_DATA_KEY)
1257 path->slots[0]--;
1258 }
1259 check_prev = 0;
1260 next_slot:
1261 leaf = path->nodes[0];
1262 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1263 ret = btrfs_next_leaf(root, path);
1264 if (ret < 0) {
1265 btrfs_abort_transaction(trans, root, ret);
1266 goto error;
1267 }
1268 if (ret > 0)
1269 break;
1270 leaf = path->nodes[0];
1271 }
1272
1273 nocow = 0;
1274 disk_bytenr = 0;
1275 num_bytes = 0;
1276 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1277
1278 if (found_key.objectid > ino ||
1279 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1280 found_key.offset > end)
1281 break;
1282
1283 if (found_key.offset > cur_offset) {
1284 extent_end = found_key.offset;
1285 extent_type = 0;
1286 goto out_check;
1287 }
1288
1289 fi = btrfs_item_ptr(leaf, path->slots[0],
1290 struct btrfs_file_extent_item);
1291 extent_type = btrfs_file_extent_type(leaf, fi);
1292
1293 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1294 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1295 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1296 extent_offset = btrfs_file_extent_offset(leaf, fi);
1297 extent_end = found_key.offset +
1298 btrfs_file_extent_num_bytes(leaf, fi);
1299 disk_num_bytes =
1300 btrfs_file_extent_disk_num_bytes(leaf, fi);
1301 if (extent_end <= start) {
1302 path->slots[0]++;
1303 goto next_slot;
1304 }
1305 if (disk_bytenr == 0)
1306 goto out_check;
1307 if (btrfs_file_extent_compression(leaf, fi) ||
1308 btrfs_file_extent_encryption(leaf, fi) ||
1309 btrfs_file_extent_other_encoding(leaf, fi))
1310 goto out_check;
1311 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1312 goto out_check;
1313 if (btrfs_extent_readonly(root, disk_bytenr))
1314 goto out_check;
1315 if (btrfs_cross_ref_exist(trans, root, ino,
1316 found_key.offset -
1317 extent_offset, disk_bytenr))
1318 goto out_check;
1319 disk_bytenr += extent_offset;
1320 disk_bytenr += cur_offset - found_key.offset;
1321 num_bytes = min(end + 1, extent_end) - cur_offset;
1322 /*
1323 * force cow if csum exists in the range.
1324 * this ensure that csum for a given extent are
1325 * either valid or do not exist.
1326 */
1327 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1328 goto out_check;
1329 nocow = 1;
1330 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1331 extent_end = found_key.offset +
1332 btrfs_file_extent_inline_len(leaf, fi);
1333 extent_end = ALIGN(extent_end, root->sectorsize);
1334 } else {
1335 BUG_ON(1);
1336 }
1337 out_check:
1338 if (extent_end <= start) {
1339 path->slots[0]++;
1340 goto next_slot;
1341 }
1342 if (!nocow) {
1343 if (cow_start == (u64)-1)
1344 cow_start = cur_offset;
1345 cur_offset = extent_end;
1346 if (cur_offset > end)
1347 break;
1348 path->slots[0]++;
1349 goto next_slot;
1350 }
1351
1352 btrfs_release_path(path);
1353 if (cow_start != (u64)-1) {
1354 ret = __cow_file_range(trans, inode, root, locked_page,
1355 cow_start, found_key.offset - 1,
1356 page_started, nr_written, 1);
1357 if (ret) {
1358 btrfs_abort_transaction(trans, root, ret);
1359 goto error;
1360 }
1361 cow_start = (u64)-1;
1362 }
1363
1364 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1365 struct extent_map *em;
1366 struct extent_map_tree *em_tree;
1367 em_tree = &BTRFS_I(inode)->extent_tree;
1368 em = alloc_extent_map();
1369 BUG_ON(!em); /* -ENOMEM */
1370 em->start = cur_offset;
1371 em->orig_start = found_key.offset - extent_offset;
1372 em->len = num_bytes;
1373 em->block_len = num_bytes;
1374 em->block_start = disk_bytenr;
1375 em->orig_block_len = disk_num_bytes;
1376 em->bdev = root->fs_info->fs_devices->latest_bdev;
1377 em->mod_start = em->start;
1378 em->mod_len = em->len;
1379 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1380 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1381 em->generation = -1;
1382 while (1) {
1383 write_lock(&em_tree->lock);
1384 ret = add_extent_mapping(em_tree, em);
1385 if (!ret)
1386 list_move(&em->list,
1387 &em_tree->modified_extents);
1388 write_unlock(&em_tree->lock);
1389 if (ret != -EEXIST) {
1390 free_extent_map(em);
1391 break;
1392 }
1393 btrfs_drop_extent_cache(inode, em->start,
1394 em->start + em->len - 1, 0);
1395 }
1396 type = BTRFS_ORDERED_PREALLOC;
1397 } else {
1398 type = BTRFS_ORDERED_NOCOW;
1399 }
1400
1401 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1402 num_bytes, num_bytes, type);
1403 BUG_ON(ret); /* -ENOMEM */
1404
1405 if (root->root_key.objectid ==
1406 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1407 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1408 num_bytes);
1409 if (ret) {
1410 btrfs_abort_transaction(trans, root, ret);
1411 goto error;
1412 }
1413 }
1414
1415 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1416 cur_offset, cur_offset + num_bytes - 1,
1417 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1418 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1419 EXTENT_SET_PRIVATE2);
1420 cur_offset = extent_end;
1421 if (cur_offset > end)
1422 break;
1423 }
1424 btrfs_release_path(path);
1425
1426 if (cur_offset <= end && cow_start == (u64)-1) {
1427 cow_start = cur_offset;
1428 cur_offset = end;
1429 }
1430
1431 if (cow_start != (u64)-1) {
1432 ret = __cow_file_range(trans, inode, root, locked_page,
1433 cow_start, end,
1434 page_started, nr_written, 1);
1435 if (ret) {
1436 btrfs_abort_transaction(trans, root, ret);
1437 goto error;
1438 }
1439 }
1440
1441 error:
1442 err = btrfs_end_transaction(trans, root);
1443 if (!ret)
1444 ret = err;
1445
1446 if (ret && cur_offset < end)
1447 extent_clear_unlock_delalloc(inode,
1448 &BTRFS_I(inode)->io_tree,
1449 cur_offset, end, locked_page,
1450 EXTENT_CLEAR_UNLOCK_PAGE |
1451 EXTENT_CLEAR_UNLOCK |
1452 EXTENT_CLEAR_DELALLOC |
1453 EXTENT_CLEAR_DIRTY |
1454 EXTENT_SET_WRITEBACK |
1455 EXTENT_END_WRITEBACK);
1456
1457 btrfs_free_path(path);
1458 return ret;
1459 }
1460
1461 /*
1462 * extent_io.c call back to do delayed allocation processing
1463 */
1464 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1465 u64 start, u64 end, int *page_started,
1466 unsigned long *nr_written)
1467 {
1468 int ret;
1469 struct btrfs_root *root = BTRFS_I(inode)->root;
1470
1471 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1472 ret = run_delalloc_nocow(inode, locked_page, start, end,
1473 page_started, 1, nr_written);
1474 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1475 ret = run_delalloc_nocow(inode, locked_page, start, end,
1476 page_started, 0, nr_written);
1477 } else if (!btrfs_test_opt(root, COMPRESS) &&
1478 !(BTRFS_I(inode)->force_compress) &&
1479 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1480 ret = cow_file_range(inode, locked_page, start, end,
1481 page_started, nr_written, 1);
1482 } else {
1483 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1484 &BTRFS_I(inode)->runtime_flags);
1485 ret = cow_file_range_async(inode, locked_page, start, end,
1486 page_started, nr_written);
1487 }
1488 return ret;
1489 }
1490
1491 static void btrfs_split_extent_hook(struct inode *inode,
1492 struct extent_state *orig, u64 split)
1493 {
1494 /* not delalloc, ignore it */
1495 if (!(orig->state & EXTENT_DELALLOC))
1496 return;
1497
1498 spin_lock(&BTRFS_I(inode)->lock);
1499 BTRFS_I(inode)->outstanding_extents++;
1500 spin_unlock(&BTRFS_I(inode)->lock);
1501 }
1502
1503 /*
1504 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1505 * extents so we can keep track of new extents that are just merged onto old
1506 * extents, such as when we are doing sequential writes, so we can properly
1507 * account for the metadata space we'll need.
1508 */
1509 static void btrfs_merge_extent_hook(struct inode *inode,
1510 struct extent_state *new,
1511 struct extent_state *other)
1512 {
1513 /* not delalloc, ignore it */
1514 if (!(other->state & EXTENT_DELALLOC))
1515 return;
1516
1517 spin_lock(&BTRFS_I(inode)->lock);
1518 BTRFS_I(inode)->outstanding_extents--;
1519 spin_unlock(&BTRFS_I(inode)->lock);
1520 }
1521
1522 /*
1523 * extent_io.c set_bit_hook, used to track delayed allocation
1524 * bytes in this file, and to maintain the list of inodes that
1525 * have pending delalloc work to be done.
1526 */
1527 static void btrfs_set_bit_hook(struct inode *inode,
1528 struct extent_state *state, int *bits)
1529 {
1530
1531 /*
1532 * set_bit and clear bit hooks normally require _irqsave/restore
1533 * but in this case, we are only testing for the DELALLOC
1534 * bit, which is only set or cleared with irqs on
1535 */
1536 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1537 struct btrfs_root *root = BTRFS_I(inode)->root;
1538 u64 len = state->end + 1 - state->start;
1539 bool do_list = !btrfs_is_free_space_inode(inode);
1540
1541 if (*bits & EXTENT_FIRST_DELALLOC) {
1542 *bits &= ~EXTENT_FIRST_DELALLOC;
1543 } else {
1544 spin_lock(&BTRFS_I(inode)->lock);
1545 BTRFS_I(inode)->outstanding_extents++;
1546 spin_unlock(&BTRFS_I(inode)->lock);
1547 }
1548
1549 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1550 root->fs_info->delalloc_batch);
1551 spin_lock(&BTRFS_I(inode)->lock);
1552 BTRFS_I(inode)->delalloc_bytes += len;
1553 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1554 &BTRFS_I(inode)->runtime_flags)) {
1555 spin_lock(&root->fs_info->delalloc_lock);
1556 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1557 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1558 &root->fs_info->delalloc_inodes);
1559 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1560 &BTRFS_I(inode)->runtime_flags);
1561 }
1562 spin_unlock(&root->fs_info->delalloc_lock);
1563 }
1564 spin_unlock(&BTRFS_I(inode)->lock);
1565 }
1566 }
1567
1568 /*
1569 * extent_io.c clear_bit_hook, see set_bit_hook for why
1570 */
1571 static void btrfs_clear_bit_hook(struct inode *inode,
1572 struct extent_state *state, int *bits)
1573 {
1574 /*
1575 * set_bit and clear bit hooks normally require _irqsave/restore
1576 * but in this case, we are only testing for the DELALLOC
1577 * bit, which is only set or cleared with irqs on
1578 */
1579 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1580 struct btrfs_root *root = BTRFS_I(inode)->root;
1581 u64 len = state->end + 1 - state->start;
1582 bool do_list = !btrfs_is_free_space_inode(inode);
1583
1584 if (*bits & EXTENT_FIRST_DELALLOC) {
1585 *bits &= ~EXTENT_FIRST_DELALLOC;
1586 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1587 spin_lock(&BTRFS_I(inode)->lock);
1588 BTRFS_I(inode)->outstanding_extents--;
1589 spin_unlock(&BTRFS_I(inode)->lock);
1590 }
1591
1592 if (*bits & EXTENT_DO_ACCOUNTING)
1593 btrfs_delalloc_release_metadata(inode, len);
1594
1595 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1596 && do_list)
1597 btrfs_free_reserved_data_space(inode, len);
1598
1599 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1600 root->fs_info->delalloc_batch);
1601 spin_lock(&BTRFS_I(inode)->lock);
1602 BTRFS_I(inode)->delalloc_bytes -= len;
1603 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1604 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1605 &BTRFS_I(inode)->runtime_flags)) {
1606 spin_lock(&root->fs_info->delalloc_lock);
1607 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1608 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1609 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1610 &BTRFS_I(inode)->runtime_flags);
1611 }
1612 spin_unlock(&root->fs_info->delalloc_lock);
1613 }
1614 spin_unlock(&BTRFS_I(inode)->lock);
1615 }
1616 }
1617
1618 /*
1619 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1620 * we don't create bios that span stripes or chunks
1621 */
1622 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1623 size_t size, struct bio *bio,
1624 unsigned long bio_flags)
1625 {
1626 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1627 u64 logical = (u64)bio->bi_sector << 9;
1628 u64 length = 0;
1629 u64 map_length;
1630 int ret;
1631
1632 if (bio_flags & EXTENT_BIO_COMPRESSED)
1633 return 0;
1634
1635 length = bio->bi_size;
1636 map_length = length;
1637 ret = btrfs_map_block(root->fs_info, rw, logical,
1638 &map_length, NULL, 0);
1639 /* Will always return 0 with map_multi == NULL */
1640 BUG_ON(ret < 0);
1641 if (map_length < length + size)
1642 return 1;
1643 return 0;
1644 }
1645
1646 /*
1647 * in order to insert checksums into the metadata in large chunks,
1648 * we wait until bio submission time. All the pages in the bio are
1649 * checksummed and sums are attached onto the ordered extent record.
1650 *
1651 * At IO completion time the cums attached on the ordered extent record
1652 * are inserted into the btree
1653 */
1654 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1655 struct bio *bio, int mirror_num,
1656 unsigned long bio_flags,
1657 u64 bio_offset)
1658 {
1659 struct btrfs_root *root = BTRFS_I(inode)->root;
1660 int ret = 0;
1661
1662 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1663 BUG_ON(ret); /* -ENOMEM */
1664 return 0;
1665 }
1666
1667 /*
1668 * in order to insert checksums into the metadata in large chunks,
1669 * we wait until bio submission time. All the pages in the bio are
1670 * checksummed and sums are attached onto the ordered extent record.
1671 *
1672 * At IO completion time the cums attached on the ordered extent record
1673 * are inserted into the btree
1674 */
1675 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1676 int mirror_num, unsigned long bio_flags,
1677 u64 bio_offset)
1678 {
1679 struct btrfs_root *root = BTRFS_I(inode)->root;
1680 int ret;
1681
1682 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1683 if (ret)
1684 bio_endio(bio, ret);
1685 return ret;
1686 }
1687
1688 /*
1689 * extent_io.c submission hook. This does the right thing for csum calculation
1690 * on write, or reading the csums from the tree before a read
1691 */
1692 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1693 int mirror_num, unsigned long bio_flags,
1694 u64 bio_offset)
1695 {
1696 struct btrfs_root *root = BTRFS_I(inode)->root;
1697 int ret = 0;
1698 int skip_sum;
1699 int metadata = 0;
1700 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1701
1702 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1703
1704 if (btrfs_is_free_space_inode(inode))
1705 metadata = 2;
1706
1707 if (!(rw & REQ_WRITE)) {
1708 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1709 if (ret)
1710 goto out;
1711
1712 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1713 ret = btrfs_submit_compressed_read(inode, bio,
1714 mirror_num,
1715 bio_flags);
1716 goto out;
1717 } else if (!skip_sum) {
1718 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1719 if (ret)
1720 goto out;
1721 }
1722 goto mapit;
1723 } else if (async && !skip_sum) {
1724 /* csum items have already been cloned */
1725 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1726 goto mapit;
1727 /* we're doing a write, do the async checksumming */
1728 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1729 inode, rw, bio, mirror_num,
1730 bio_flags, bio_offset,
1731 __btrfs_submit_bio_start,
1732 __btrfs_submit_bio_done);
1733 goto out;
1734 } else if (!skip_sum) {
1735 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1736 if (ret)
1737 goto out;
1738 }
1739
1740 mapit:
1741 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1742
1743 out:
1744 if (ret < 0)
1745 bio_endio(bio, ret);
1746 return ret;
1747 }
1748
1749 /*
1750 * given a list of ordered sums record them in the inode. This happens
1751 * at IO completion time based on sums calculated at bio submission time.
1752 */
1753 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1754 struct inode *inode, u64 file_offset,
1755 struct list_head *list)
1756 {
1757 struct btrfs_ordered_sum *sum;
1758
1759 list_for_each_entry(sum, list, list) {
1760 trans->adding_csums = 1;
1761 btrfs_csum_file_blocks(trans,
1762 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1763 trans->adding_csums = 0;
1764 }
1765 return 0;
1766 }
1767
1768 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1769 struct extent_state **cached_state)
1770 {
1771 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1772 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1773 cached_state, GFP_NOFS);
1774 }
1775
1776 /* see btrfs_writepage_start_hook for details on why this is required */
1777 struct btrfs_writepage_fixup {
1778 struct page *page;
1779 struct btrfs_work work;
1780 };
1781
1782 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1783 {
1784 struct btrfs_writepage_fixup *fixup;
1785 struct btrfs_ordered_extent *ordered;
1786 struct extent_state *cached_state = NULL;
1787 struct page *page;
1788 struct inode *inode;
1789 u64 page_start;
1790 u64 page_end;
1791 int ret;
1792
1793 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1794 page = fixup->page;
1795 again:
1796 lock_page(page);
1797 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1798 ClearPageChecked(page);
1799 goto out_page;
1800 }
1801
1802 inode = page->mapping->host;
1803 page_start = page_offset(page);
1804 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1805
1806 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1807 &cached_state);
1808
1809 /* already ordered? We're done */
1810 if (PagePrivate2(page))
1811 goto out;
1812
1813 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1814 if (ordered) {
1815 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1816 page_end, &cached_state, GFP_NOFS);
1817 unlock_page(page);
1818 btrfs_start_ordered_extent(inode, ordered, 1);
1819 btrfs_put_ordered_extent(ordered);
1820 goto again;
1821 }
1822
1823 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1824 if (ret) {
1825 mapping_set_error(page->mapping, ret);
1826 end_extent_writepage(page, ret, page_start, page_end);
1827 ClearPageChecked(page);
1828 goto out;
1829 }
1830
1831 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1832 ClearPageChecked(page);
1833 set_page_dirty(page);
1834 out:
1835 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1836 &cached_state, GFP_NOFS);
1837 out_page:
1838 unlock_page(page);
1839 page_cache_release(page);
1840 kfree(fixup);
1841 }
1842
1843 /*
1844 * There are a few paths in the higher layers of the kernel that directly
1845 * set the page dirty bit without asking the filesystem if it is a
1846 * good idea. This causes problems because we want to make sure COW
1847 * properly happens and the data=ordered rules are followed.
1848 *
1849 * In our case any range that doesn't have the ORDERED bit set
1850 * hasn't been properly setup for IO. We kick off an async process
1851 * to fix it up. The async helper will wait for ordered extents, set
1852 * the delalloc bit and make it safe to write the page.
1853 */
1854 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1855 {
1856 struct inode *inode = page->mapping->host;
1857 struct btrfs_writepage_fixup *fixup;
1858 struct btrfs_root *root = BTRFS_I(inode)->root;
1859
1860 /* this page is properly in the ordered list */
1861 if (TestClearPagePrivate2(page))
1862 return 0;
1863
1864 if (PageChecked(page))
1865 return -EAGAIN;
1866
1867 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1868 if (!fixup)
1869 return -EAGAIN;
1870
1871 SetPageChecked(page);
1872 page_cache_get(page);
1873 fixup->work.func = btrfs_writepage_fixup_worker;
1874 fixup->page = page;
1875 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1876 return -EBUSY;
1877 }
1878
1879 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1880 struct inode *inode, u64 file_pos,
1881 u64 disk_bytenr, u64 disk_num_bytes,
1882 u64 num_bytes, u64 ram_bytes,
1883 u8 compression, u8 encryption,
1884 u16 other_encoding, int extent_type)
1885 {
1886 struct btrfs_root *root = BTRFS_I(inode)->root;
1887 struct btrfs_file_extent_item *fi;
1888 struct btrfs_path *path;
1889 struct extent_buffer *leaf;
1890 struct btrfs_key ins;
1891 int ret;
1892
1893 path = btrfs_alloc_path();
1894 if (!path)
1895 return -ENOMEM;
1896
1897 path->leave_spinning = 1;
1898
1899 /*
1900 * we may be replacing one extent in the tree with another.
1901 * The new extent is pinned in the extent map, and we don't want
1902 * to drop it from the cache until it is completely in the btree.
1903 *
1904 * So, tell btrfs_drop_extents to leave this extent in the cache.
1905 * the caller is expected to unpin it and allow it to be merged
1906 * with the others.
1907 */
1908 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1909 file_pos + num_bytes, 0);
1910 if (ret)
1911 goto out;
1912
1913 ins.objectid = btrfs_ino(inode);
1914 ins.offset = file_pos;
1915 ins.type = BTRFS_EXTENT_DATA_KEY;
1916 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1917 if (ret)
1918 goto out;
1919 leaf = path->nodes[0];
1920 fi = btrfs_item_ptr(leaf, path->slots[0],
1921 struct btrfs_file_extent_item);
1922 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1923 btrfs_set_file_extent_type(leaf, fi, extent_type);
1924 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1925 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1926 btrfs_set_file_extent_offset(leaf, fi, 0);
1927 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1928 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1929 btrfs_set_file_extent_compression(leaf, fi, compression);
1930 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1931 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1932
1933 btrfs_mark_buffer_dirty(leaf);
1934 btrfs_release_path(path);
1935
1936 inode_add_bytes(inode, num_bytes);
1937
1938 ins.objectid = disk_bytenr;
1939 ins.offset = disk_num_bytes;
1940 ins.type = BTRFS_EXTENT_ITEM_KEY;
1941 ret = btrfs_alloc_reserved_file_extent(trans, root,
1942 root->root_key.objectid,
1943 btrfs_ino(inode), file_pos, &ins);
1944 out:
1945 btrfs_free_path(path);
1946
1947 return ret;
1948 }
1949
1950 /* snapshot-aware defrag */
1951 struct sa_defrag_extent_backref {
1952 struct rb_node node;
1953 struct old_sa_defrag_extent *old;
1954 u64 root_id;
1955 u64 inum;
1956 u64 file_pos;
1957 u64 extent_offset;
1958 u64 num_bytes;
1959 u64 generation;
1960 };
1961
1962 struct old_sa_defrag_extent {
1963 struct list_head list;
1964 struct new_sa_defrag_extent *new;
1965
1966 u64 extent_offset;
1967 u64 bytenr;
1968 u64 offset;
1969 u64 len;
1970 int count;
1971 };
1972
1973 struct new_sa_defrag_extent {
1974 struct rb_root root;
1975 struct list_head head;
1976 struct btrfs_path *path;
1977 struct inode *inode;
1978 u64 file_pos;
1979 u64 len;
1980 u64 bytenr;
1981 u64 disk_len;
1982 u8 compress_type;
1983 };
1984
1985 static int backref_comp(struct sa_defrag_extent_backref *b1,
1986 struct sa_defrag_extent_backref *b2)
1987 {
1988 if (b1->root_id < b2->root_id)
1989 return -1;
1990 else if (b1->root_id > b2->root_id)
1991 return 1;
1992
1993 if (b1->inum < b2->inum)
1994 return -1;
1995 else if (b1->inum > b2->inum)
1996 return 1;
1997
1998 if (b1->file_pos < b2->file_pos)
1999 return -1;
2000 else if (b1->file_pos > b2->file_pos)
2001 return 1;
2002
2003 /*
2004 * [------------------------------] ===> (a range of space)
2005 * |<--->| |<---->| =============> (fs/file tree A)
2006 * |<---------------------------->| ===> (fs/file tree B)
2007 *
2008 * A range of space can refer to two file extents in one tree while
2009 * refer to only one file extent in another tree.
2010 *
2011 * So we may process a disk offset more than one time(two extents in A)
2012 * and locate at the same extent(one extent in B), then insert two same
2013 * backrefs(both refer to the extent in B).
2014 */
2015 return 0;
2016 }
2017
2018 static void backref_insert(struct rb_root *root,
2019 struct sa_defrag_extent_backref *backref)
2020 {
2021 struct rb_node **p = &root->rb_node;
2022 struct rb_node *parent = NULL;
2023 struct sa_defrag_extent_backref *entry;
2024 int ret;
2025
2026 while (*p) {
2027 parent = *p;
2028 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2029
2030 ret = backref_comp(backref, entry);
2031 if (ret < 0)
2032 p = &(*p)->rb_left;
2033 else
2034 p = &(*p)->rb_right;
2035 }
2036
2037 rb_link_node(&backref->node, parent, p);
2038 rb_insert_color(&backref->node, root);
2039 }
2040
2041 /*
2042 * Note the backref might has changed, and in this case we just return 0.
2043 */
2044 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2045 void *ctx)
2046 {
2047 struct btrfs_file_extent_item *extent;
2048 struct btrfs_fs_info *fs_info;
2049 struct old_sa_defrag_extent *old = ctx;
2050 struct new_sa_defrag_extent *new = old->new;
2051 struct btrfs_path *path = new->path;
2052 struct btrfs_key key;
2053 struct btrfs_root *root;
2054 struct sa_defrag_extent_backref *backref;
2055 struct extent_buffer *leaf;
2056 struct inode *inode = new->inode;
2057 int slot;
2058 int ret;
2059 u64 extent_offset;
2060 u64 num_bytes;
2061
2062 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2063 inum == btrfs_ino(inode))
2064 return 0;
2065
2066 key.objectid = root_id;
2067 key.type = BTRFS_ROOT_ITEM_KEY;
2068 key.offset = (u64)-1;
2069
2070 fs_info = BTRFS_I(inode)->root->fs_info;
2071 root = btrfs_read_fs_root_no_name(fs_info, &key);
2072 if (IS_ERR(root)) {
2073 if (PTR_ERR(root) == -ENOENT)
2074 return 0;
2075 WARN_ON(1);
2076 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2077 inum, offset, root_id);
2078 return PTR_ERR(root);
2079 }
2080
2081 key.objectid = inum;
2082 key.type = BTRFS_EXTENT_DATA_KEY;
2083 if (offset > (u64)-1 << 32)
2084 key.offset = 0;
2085 else
2086 key.offset = offset;
2087
2088 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2089 if (ret < 0) {
2090 WARN_ON(1);
2091 return ret;
2092 }
2093
2094 while (1) {
2095 cond_resched();
2096
2097 leaf = path->nodes[0];
2098 slot = path->slots[0];
2099
2100 if (slot >= btrfs_header_nritems(leaf)) {
2101 ret = btrfs_next_leaf(root, path);
2102 if (ret < 0) {
2103 goto out;
2104 } else if (ret > 0) {
2105 ret = 0;
2106 goto out;
2107 }
2108 continue;
2109 }
2110
2111 path->slots[0]++;
2112
2113 btrfs_item_key_to_cpu(leaf, &key, slot);
2114
2115 if (key.objectid > inum)
2116 goto out;
2117
2118 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2119 continue;
2120
2121 extent = btrfs_item_ptr(leaf, slot,
2122 struct btrfs_file_extent_item);
2123
2124 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2125 continue;
2126
2127 extent_offset = btrfs_file_extent_offset(leaf, extent);
2128 if (key.offset - extent_offset != offset)
2129 continue;
2130
2131 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2132 if (extent_offset >= old->extent_offset + old->offset +
2133 old->len || extent_offset + num_bytes <=
2134 old->extent_offset + old->offset)
2135 continue;
2136
2137 break;
2138 }
2139
2140 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2141 if (!backref) {
2142 ret = -ENOENT;
2143 goto out;
2144 }
2145
2146 backref->root_id = root_id;
2147 backref->inum = inum;
2148 backref->file_pos = offset + extent_offset;
2149 backref->num_bytes = num_bytes;
2150 backref->extent_offset = extent_offset;
2151 backref->generation = btrfs_file_extent_generation(leaf, extent);
2152 backref->old = old;
2153 backref_insert(&new->root, backref);
2154 old->count++;
2155 out:
2156 btrfs_release_path(path);
2157 WARN_ON(ret);
2158 return ret;
2159 }
2160
2161 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2162 struct new_sa_defrag_extent *new)
2163 {
2164 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2165 struct old_sa_defrag_extent *old, *tmp;
2166 int ret;
2167
2168 new->path = path;
2169
2170 list_for_each_entry_safe(old, tmp, &new->head, list) {
2171 ret = iterate_inodes_from_logical(old->bytenr, fs_info,
2172 path, record_one_backref,
2173 old);
2174 BUG_ON(ret < 0 && ret != -ENOENT);
2175
2176 /* no backref to be processed for this extent */
2177 if (!old->count) {
2178 list_del(&old->list);
2179 kfree(old);
2180 }
2181 }
2182
2183 if (list_empty(&new->head))
2184 return false;
2185
2186 return true;
2187 }
2188
2189 static int relink_is_mergable(struct extent_buffer *leaf,
2190 struct btrfs_file_extent_item *fi,
2191 u64 disk_bytenr)
2192 {
2193 if (btrfs_file_extent_disk_bytenr(leaf, fi) != disk_bytenr)
2194 return 0;
2195
2196 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2197 return 0;
2198
2199 if (btrfs_file_extent_compression(leaf, fi) ||
2200 btrfs_file_extent_encryption(leaf, fi) ||
2201 btrfs_file_extent_other_encoding(leaf, fi))
2202 return 0;
2203
2204 return 1;
2205 }
2206
2207 /*
2208 * Note the backref might has changed, and in this case we just return 0.
2209 */
2210 static noinline int relink_extent_backref(struct btrfs_path *path,
2211 struct sa_defrag_extent_backref *prev,
2212 struct sa_defrag_extent_backref *backref)
2213 {
2214 struct btrfs_file_extent_item *extent;
2215 struct btrfs_file_extent_item *item;
2216 struct btrfs_ordered_extent *ordered;
2217 struct btrfs_trans_handle *trans;
2218 struct btrfs_fs_info *fs_info;
2219 struct btrfs_root *root;
2220 struct btrfs_key key;
2221 struct extent_buffer *leaf;
2222 struct old_sa_defrag_extent *old = backref->old;
2223 struct new_sa_defrag_extent *new = old->new;
2224 struct inode *src_inode = new->inode;
2225 struct inode *inode;
2226 struct extent_state *cached = NULL;
2227 int ret = 0;
2228 u64 start;
2229 u64 len;
2230 u64 lock_start;
2231 u64 lock_end;
2232 bool merge = false;
2233 int index;
2234
2235 if (prev && prev->root_id == backref->root_id &&
2236 prev->inum == backref->inum &&
2237 prev->file_pos + prev->num_bytes == backref->file_pos)
2238 merge = true;
2239
2240 /* step 1: get root */
2241 key.objectid = backref->root_id;
2242 key.type = BTRFS_ROOT_ITEM_KEY;
2243 key.offset = (u64)-1;
2244
2245 fs_info = BTRFS_I(src_inode)->root->fs_info;
2246 index = srcu_read_lock(&fs_info->subvol_srcu);
2247
2248 root = btrfs_read_fs_root_no_name(fs_info, &key);
2249 if (IS_ERR(root)) {
2250 srcu_read_unlock(&fs_info->subvol_srcu, index);
2251 if (PTR_ERR(root) == -ENOENT)
2252 return 0;
2253 return PTR_ERR(root);
2254 }
2255 if (btrfs_root_refs(&root->root_item) == 0) {
2256 srcu_read_unlock(&fs_info->subvol_srcu, index);
2257 /* parse ENOENT to 0 */
2258 return 0;
2259 }
2260
2261 /* step 2: get inode */
2262 key.objectid = backref->inum;
2263 key.type = BTRFS_INODE_ITEM_KEY;
2264 key.offset = 0;
2265
2266 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2267 if (IS_ERR(inode)) {
2268 srcu_read_unlock(&fs_info->subvol_srcu, index);
2269 return 0;
2270 }
2271
2272 srcu_read_unlock(&fs_info->subvol_srcu, index);
2273
2274 /* step 3: relink backref */
2275 lock_start = backref->file_pos;
2276 lock_end = backref->file_pos + backref->num_bytes - 1;
2277 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2278 0, &cached);
2279
2280 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2281 if (ordered) {
2282 btrfs_put_ordered_extent(ordered);
2283 goto out_unlock;
2284 }
2285
2286 trans = btrfs_join_transaction(root);
2287 if (IS_ERR(trans)) {
2288 ret = PTR_ERR(trans);
2289 goto out_unlock;
2290 }
2291
2292 key.objectid = backref->inum;
2293 key.type = BTRFS_EXTENT_DATA_KEY;
2294 key.offset = backref->file_pos;
2295
2296 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2297 if (ret < 0) {
2298 goto out_free_path;
2299 } else if (ret > 0) {
2300 ret = 0;
2301 goto out_free_path;
2302 }
2303
2304 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2305 struct btrfs_file_extent_item);
2306
2307 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2308 backref->generation)
2309 goto out_free_path;
2310
2311 btrfs_release_path(path);
2312
2313 start = backref->file_pos;
2314 if (backref->extent_offset < old->extent_offset + old->offset)
2315 start += old->extent_offset + old->offset -
2316 backref->extent_offset;
2317
2318 len = min(backref->extent_offset + backref->num_bytes,
2319 old->extent_offset + old->offset + old->len);
2320 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2321
2322 ret = btrfs_drop_extents(trans, root, inode, start,
2323 start + len, 1);
2324 if (ret)
2325 goto out_free_path;
2326 again:
2327 key.objectid = btrfs_ino(inode);
2328 key.type = BTRFS_EXTENT_DATA_KEY;
2329 key.offset = start;
2330
2331 path->leave_spinning = 1;
2332 if (merge) {
2333 struct btrfs_file_extent_item *fi;
2334 u64 extent_len;
2335 struct btrfs_key found_key;
2336
2337 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2338 if (ret < 0)
2339 goto out_free_path;
2340
2341 path->slots[0]--;
2342 leaf = path->nodes[0];
2343 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2344
2345 fi = btrfs_item_ptr(leaf, path->slots[0],
2346 struct btrfs_file_extent_item);
2347 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2348
2349 if (relink_is_mergable(leaf, fi, new->bytenr) &&
2350 extent_len + found_key.offset == start) {
2351 btrfs_set_file_extent_num_bytes(leaf, fi,
2352 extent_len + len);
2353 btrfs_mark_buffer_dirty(leaf);
2354 inode_add_bytes(inode, len);
2355
2356 ret = 1;
2357 goto out_free_path;
2358 } else {
2359 merge = false;
2360 btrfs_release_path(path);
2361 goto again;
2362 }
2363 }
2364
2365 ret = btrfs_insert_empty_item(trans, root, path, &key,
2366 sizeof(*extent));
2367 if (ret) {
2368 btrfs_abort_transaction(trans, root, ret);
2369 goto out_free_path;
2370 }
2371
2372 leaf = path->nodes[0];
2373 item = btrfs_item_ptr(leaf, path->slots[0],
2374 struct btrfs_file_extent_item);
2375 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2376 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2377 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2378 btrfs_set_file_extent_num_bytes(leaf, item, len);
2379 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2380 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2381 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2382 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2383 btrfs_set_file_extent_encryption(leaf, item, 0);
2384 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2385
2386 btrfs_mark_buffer_dirty(leaf);
2387 inode_add_bytes(inode, len);
2388 btrfs_release_path(path);
2389
2390 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2391 new->disk_len, 0,
2392 backref->root_id, backref->inum,
2393 new->file_pos, 0); /* start - extent_offset */
2394 if (ret) {
2395 btrfs_abort_transaction(trans, root, ret);
2396 goto out_free_path;
2397 }
2398
2399 ret = 1;
2400 out_free_path:
2401 btrfs_release_path(path);
2402 path->leave_spinning = 0;
2403 btrfs_end_transaction(trans, root);
2404 out_unlock:
2405 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2406 &cached, GFP_NOFS);
2407 iput(inode);
2408 return ret;
2409 }
2410
2411 static void relink_file_extents(struct new_sa_defrag_extent *new)
2412 {
2413 struct btrfs_path *path;
2414 struct old_sa_defrag_extent *old, *tmp;
2415 struct sa_defrag_extent_backref *backref;
2416 struct sa_defrag_extent_backref *prev = NULL;
2417 struct inode *inode;
2418 struct btrfs_root *root;
2419 struct rb_node *node;
2420 int ret;
2421
2422 inode = new->inode;
2423 root = BTRFS_I(inode)->root;
2424
2425 path = btrfs_alloc_path();
2426 if (!path)
2427 return;
2428
2429 if (!record_extent_backrefs(path, new)) {
2430 btrfs_free_path(path);
2431 goto out;
2432 }
2433 btrfs_release_path(path);
2434
2435 while (1) {
2436 node = rb_first(&new->root);
2437 if (!node)
2438 break;
2439 rb_erase(node, &new->root);
2440
2441 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2442
2443 ret = relink_extent_backref(path, prev, backref);
2444 WARN_ON(ret < 0);
2445
2446 kfree(prev);
2447
2448 if (ret == 1)
2449 prev = backref;
2450 else
2451 prev = NULL;
2452 cond_resched();
2453 }
2454 kfree(prev);
2455
2456 btrfs_free_path(path);
2457
2458 list_for_each_entry_safe(old, tmp, &new->head, list) {
2459 list_del(&old->list);
2460 kfree(old);
2461 }
2462 out:
2463 atomic_dec(&root->fs_info->defrag_running);
2464 wake_up(&root->fs_info->transaction_wait);
2465
2466 kfree(new);
2467 }
2468
2469 static struct new_sa_defrag_extent *
2470 record_old_file_extents(struct inode *inode,
2471 struct btrfs_ordered_extent *ordered)
2472 {
2473 struct btrfs_root *root = BTRFS_I(inode)->root;
2474 struct btrfs_path *path;
2475 struct btrfs_key key;
2476 struct old_sa_defrag_extent *old, *tmp;
2477 struct new_sa_defrag_extent *new;
2478 int ret;
2479
2480 new = kmalloc(sizeof(*new), GFP_NOFS);
2481 if (!new)
2482 return NULL;
2483
2484 new->inode = inode;
2485 new->file_pos = ordered->file_offset;
2486 new->len = ordered->len;
2487 new->bytenr = ordered->start;
2488 new->disk_len = ordered->disk_len;
2489 new->compress_type = ordered->compress_type;
2490 new->root = RB_ROOT;
2491 INIT_LIST_HEAD(&new->head);
2492
2493 path = btrfs_alloc_path();
2494 if (!path)
2495 goto out_kfree;
2496
2497 key.objectid = btrfs_ino(inode);
2498 key.type = BTRFS_EXTENT_DATA_KEY;
2499 key.offset = new->file_pos;
2500
2501 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2502 if (ret < 0)
2503 goto out_free_path;
2504 if (ret > 0 && path->slots[0] > 0)
2505 path->slots[0]--;
2506
2507 /* find out all the old extents for the file range */
2508 while (1) {
2509 struct btrfs_file_extent_item *extent;
2510 struct extent_buffer *l;
2511 int slot;
2512 u64 num_bytes;
2513 u64 offset;
2514 u64 end;
2515 u64 disk_bytenr;
2516 u64 extent_offset;
2517
2518 l = path->nodes[0];
2519 slot = path->slots[0];
2520
2521 if (slot >= btrfs_header_nritems(l)) {
2522 ret = btrfs_next_leaf(root, path);
2523 if (ret < 0)
2524 goto out_free_list;
2525 else if (ret > 0)
2526 break;
2527 continue;
2528 }
2529
2530 btrfs_item_key_to_cpu(l, &key, slot);
2531
2532 if (key.objectid != btrfs_ino(inode))
2533 break;
2534 if (key.type != BTRFS_EXTENT_DATA_KEY)
2535 break;
2536 if (key.offset >= new->file_pos + new->len)
2537 break;
2538
2539 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2540
2541 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2542 if (key.offset + num_bytes < new->file_pos)
2543 goto next;
2544
2545 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2546 if (!disk_bytenr)
2547 goto next;
2548
2549 extent_offset = btrfs_file_extent_offset(l, extent);
2550
2551 old = kmalloc(sizeof(*old), GFP_NOFS);
2552 if (!old)
2553 goto out_free_list;
2554
2555 offset = max(new->file_pos, key.offset);
2556 end = min(new->file_pos + new->len, key.offset + num_bytes);
2557
2558 old->bytenr = disk_bytenr;
2559 old->extent_offset = extent_offset;
2560 old->offset = offset - key.offset;
2561 old->len = end - offset;
2562 old->new = new;
2563 old->count = 0;
2564 list_add_tail(&old->list, &new->head);
2565 next:
2566 path->slots[0]++;
2567 cond_resched();
2568 }
2569
2570 btrfs_free_path(path);
2571 atomic_inc(&root->fs_info->defrag_running);
2572
2573 return new;
2574
2575 out_free_list:
2576 list_for_each_entry_safe(old, tmp, &new->head, list) {
2577 list_del(&old->list);
2578 kfree(old);
2579 }
2580 out_free_path:
2581 btrfs_free_path(path);
2582 out_kfree:
2583 kfree(new);
2584 return NULL;
2585 }
2586
2587 /*
2588 * helper function for btrfs_finish_ordered_io, this
2589 * just reads in some of the csum leaves to prime them into ram
2590 * before we start the transaction. It limits the amount of btree
2591 * reads required while inside the transaction.
2592 */
2593 /* as ordered data IO finishes, this gets called so we can finish
2594 * an ordered extent if the range of bytes in the file it covers are
2595 * fully written.
2596 */
2597 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2598 {
2599 struct inode *inode = ordered_extent->inode;
2600 struct btrfs_root *root = BTRFS_I(inode)->root;
2601 struct btrfs_trans_handle *trans = NULL;
2602 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2603 struct extent_state *cached_state = NULL;
2604 struct new_sa_defrag_extent *new = NULL;
2605 int compress_type = 0;
2606 int ret;
2607 bool nolock;
2608
2609 nolock = btrfs_is_free_space_inode(inode);
2610
2611 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2612 ret = -EIO;
2613 goto out;
2614 }
2615
2616 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2617 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2618 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2619 if (nolock)
2620 trans = btrfs_join_transaction_nolock(root);
2621 else
2622 trans = btrfs_join_transaction(root);
2623 if (IS_ERR(trans)) {
2624 ret = PTR_ERR(trans);
2625 trans = NULL;
2626 goto out;
2627 }
2628 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2629 ret = btrfs_update_inode_fallback(trans, root, inode);
2630 if (ret) /* -ENOMEM or corruption */
2631 btrfs_abort_transaction(trans, root, ret);
2632 goto out;
2633 }
2634
2635 lock_extent_bits(io_tree, ordered_extent->file_offset,
2636 ordered_extent->file_offset + ordered_extent->len - 1,
2637 0, &cached_state);
2638
2639 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2640 ordered_extent->file_offset + ordered_extent->len - 1,
2641 EXTENT_DEFRAG, 1, cached_state);
2642 if (ret) {
2643 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2644 if (last_snapshot >= BTRFS_I(inode)->generation)
2645 /* the inode is shared */
2646 new = record_old_file_extents(inode, ordered_extent);
2647
2648 clear_extent_bit(io_tree, ordered_extent->file_offset,
2649 ordered_extent->file_offset + ordered_extent->len - 1,
2650 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2651 }
2652
2653 if (nolock)
2654 trans = btrfs_join_transaction_nolock(root);
2655 else
2656 trans = btrfs_join_transaction(root);
2657 if (IS_ERR(trans)) {
2658 ret = PTR_ERR(trans);
2659 trans = NULL;
2660 goto out_unlock;
2661 }
2662 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2663
2664 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2665 compress_type = ordered_extent->compress_type;
2666 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2667 BUG_ON(compress_type);
2668 ret = btrfs_mark_extent_written(trans, inode,
2669 ordered_extent->file_offset,
2670 ordered_extent->file_offset +
2671 ordered_extent->len);
2672 } else {
2673 BUG_ON(root == root->fs_info->tree_root);
2674 ret = insert_reserved_file_extent(trans, inode,
2675 ordered_extent->file_offset,
2676 ordered_extent->start,
2677 ordered_extent->disk_len,
2678 ordered_extent->len,
2679 ordered_extent->len,
2680 compress_type, 0, 0,
2681 BTRFS_FILE_EXTENT_REG);
2682 }
2683 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2684 ordered_extent->file_offset, ordered_extent->len,
2685 trans->transid);
2686 if (ret < 0) {
2687 btrfs_abort_transaction(trans, root, ret);
2688 goto out_unlock;
2689 }
2690
2691 add_pending_csums(trans, inode, ordered_extent->file_offset,
2692 &ordered_extent->list);
2693
2694 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2695 ret = btrfs_update_inode_fallback(trans, root, inode);
2696 if (ret) { /* -ENOMEM or corruption */
2697 btrfs_abort_transaction(trans, root, ret);
2698 goto out_unlock;
2699 }
2700 ret = 0;
2701 out_unlock:
2702 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2703 ordered_extent->file_offset +
2704 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2705 out:
2706 if (root != root->fs_info->tree_root)
2707 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2708 if (trans)
2709 btrfs_end_transaction(trans, root);
2710
2711 if (ret) {
2712 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2713 ordered_extent->file_offset +
2714 ordered_extent->len - 1, NULL, GFP_NOFS);
2715
2716 /*
2717 * If the ordered extent had an IOERR or something else went
2718 * wrong we need to return the space for this ordered extent
2719 * back to the allocator.
2720 */
2721 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2722 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2723 btrfs_free_reserved_extent(root, ordered_extent->start,
2724 ordered_extent->disk_len);
2725 }
2726
2727
2728 /*
2729 * This needs to be done to make sure anybody waiting knows we are done
2730 * updating everything for this ordered extent.
2731 */
2732 btrfs_remove_ordered_extent(inode, ordered_extent);
2733
2734 /* for snapshot-aware defrag */
2735 if (new)
2736 relink_file_extents(new);
2737
2738 /* once for us */
2739 btrfs_put_ordered_extent(ordered_extent);
2740 /* once for the tree */
2741 btrfs_put_ordered_extent(ordered_extent);
2742
2743 return ret;
2744 }
2745
2746 static void finish_ordered_fn(struct btrfs_work *work)
2747 {
2748 struct btrfs_ordered_extent *ordered_extent;
2749 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2750 btrfs_finish_ordered_io(ordered_extent);
2751 }
2752
2753 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2754 struct extent_state *state, int uptodate)
2755 {
2756 struct inode *inode = page->mapping->host;
2757 struct btrfs_root *root = BTRFS_I(inode)->root;
2758 struct btrfs_ordered_extent *ordered_extent = NULL;
2759 struct btrfs_workers *workers;
2760
2761 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2762
2763 ClearPagePrivate2(page);
2764 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2765 end - start + 1, uptodate))
2766 return 0;
2767
2768 ordered_extent->work.func = finish_ordered_fn;
2769 ordered_extent->work.flags = 0;
2770
2771 if (btrfs_is_free_space_inode(inode))
2772 workers = &root->fs_info->endio_freespace_worker;
2773 else
2774 workers = &root->fs_info->endio_write_workers;
2775 btrfs_queue_worker(workers, &ordered_extent->work);
2776
2777 return 0;
2778 }
2779
2780 /*
2781 * when reads are done, we need to check csums to verify the data is correct
2782 * if there's a match, we allow the bio to finish. If not, the code in
2783 * extent_io.c will try to find good copies for us.
2784 */
2785 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2786 struct extent_state *state, int mirror)
2787 {
2788 size_t offset = start - page_offset(page);
2789 struct inode *inode = page->mapping->host;
2790 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2791 char *kaddr;
2792 u64 private = ~(u32)0;
2793 int ret;
2794 struct btrfs_root *root = BTRFS_I(inode)->root;
2795 u32 csum = ~(u32)0;
2796 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2797 DEFAULT_RATELIMIT_BURST);
2798
2799 if (PageChecked(page)) {
2800 ClearPageChecked(page);
2801 goto good;
2802 }
2803
2804 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2805 goto good;
2806
2807 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2808 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2809 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2810 GFP_NOFS);
2811 return 0;
2812 }
2813
2814 if (state && state->start == start) {
2815 private = state->private;
2816 ret = 0;
2817 } else {
2818 ret = get_state_private(io_tree, start, &private);
2819 }
2820 kaddr = kmap_atomic(page);
2821 if (ret)
2822 goto zeroit;
2823
2824 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2825 btrfs_csum_final(csum, (char *)&csum);
2826 if (csum != private)
2827 goto zeroit;
2828
2829 kunmap_atomic(kaddr);
2830 good:
2831 return 0;
2832
2833 zeroit:
2834 if (__ratelimit(&_rs))
2835 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u private %llu",
2836 (unsigned long long)btrfs_ino(page->mapping->host),
2837 (unsigned long long)start, csum,
2838 (unsigned long long)private);
2839 memset(kaddr + offset, 1, end - start + 1);
2840 flush_dcache_page(page);
2841 kunmap_atomic(kaddr);
2842 if (private == 0)
2843 return 0;
2844 return -EIO;
2845 }
2846
2847 struct delayed_iput {
2848 struct list_head list;
2849 struct inode *inode;
2850 };
2851
2852 /* JDM: If this is fs-wide, why can't we add a pointer to
2853 * btrfs_inode instead and avoid the allocation? */
2854 void btrfs_add_delayed_iput(struct inode *inode)
2855 {
2856 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2857 struct delayed_iput *delayed;
2858
2859 if (atomic_add_unless(&inode->i_count, -1, 1))
2860 return;
2861
2862 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2863 delayed->inode = inode;
2864
2865 spin_lock(&fs_info->delayed_iput_lock);
2866 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2867 spin_unlock(&fs_info->delayed_iput_lock);
2868 }
2869
2870 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2871 {
2872 LIST_HEAD(list);
2873 struct btrfs_fs_info *fs_info = root->fs_info;
2874 struct delayed_iput *delayed;
2875 int empty;
2876
2877 spin_lock(&fs_info->delayed_iput_lock);
2878 empty = list_empty(&fs_info->delayed_iputs);
2879 spin_unlock(&fs_info->delayed_iput_lock);
2880 if (empty)
2881 return;
2882
2883 spin_lock(&fs_info->delayed_iput_lock);
2884 list_splice_init(&fs_info->delayed_iputs, &list);
2885 spin_unlock(&fs_info->delayed_iput_lock);
2886
2887 while (!list_empty(&list)) {
2888 delayed = list_entry(list.next, struct delayed_iput, list);
2889 list_del(&delayed->list);
2890 iput(delayed->inode);
2891 kfree(delayed);
2892 }
2893 }
2894
2895 /*
2896 * This is called in transaction commit time. If there are no orphan
2897 * files in the subvolume, it removes orphan item and frees block_rsv
2898 * structure.
2899 */
2900 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2901 struct btrfs_root *root)
2902 {
2903 struct btrfs_block_rsv *block_rsv;
2904 int ret;
2905
2906 if (atomic_read(&root->orphan_inodes) ||
2907 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2908 return;
2909
2910 spin_lock(&root->orphan_lock);
2911 if (atomic_read(&root->orphan_inodes)) {
2912 spin_unlock(&root->orphan_lock);
2913 return;
2914 }
2915
2916 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2917 spin_unlock(&root->orphan_lock);
2918 return;
2919 }
2920
2921 block_rsv = root->orphan_block_rsv;
2922 root->orphan_block_rsv = NULL;
2923 spin_unlock(&root->orphan_lock);
2924
2925 if (root->orphan_item_inserted &&
2926 btrfs_root_refs(&root->root_item) > 0) {
2927 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2928 root->root_key.objectid);
2929 BUG_ON(ret);
2930 root->orphan_item_inserted = 0;
2931 }
2932
2933 if (block_rsv) {
2934 WARN_ON(block_rsv->size > 0);
2935 btrfs_free_block_rsv(root, block_rsv);
2936 }
2937 }
2938
2939 /*
2940 * This creates an orphan entry for the given inode in case something goes
2941 * wrong in the middle of an unlink/truncate.
2942 *
2943 * NOTE: caller of this function should reserve 5 units of metadata for
2944 * this function.
2945 */
2946 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2947 {
2948 struct btrfs_root *root = BTRFS_I(inode)->root;
2949 struct btrfs_block_rsv *block_rsv = NULL;
2950 int reserve = 0;
2951 int insert = 0;
2952 int ret;
2953
2954 if (!root->orphan_block_rsv) {
2955 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2956 if (!block_rsv)
2957 return -ENOMEM;
2958 }
2959
2960 spin_lock(&root->orphan_lock);
2961 if (!root->orphan_block_rsv) {
2962 root->orphan_block_rsv = block_rsv;
2963 } else if (block_rsv) {
2964 btrfs_free_block_rsv(root, block_rsv);
2965 block_rsv = NULL;
2966 }
2967
2968 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2969 &BTRFS_I(inode)->runtime_flags)) {
2970 #if 0
2971 /*
2972 * For proper ENOSPC handling, we should do orphan
2973 * cleanup when mounting. But this introduces backward
2974 * compatibility issue.
2975 */
2976 if (!xchg(&root->orphan_item_inserted, 1))
2977 insert = 2;
2978 else
2979 insert = 1;
2980 #endif
2981 insert = 1;
2982 atomic_inc(&root->orphan_inodes);
2983 }
2984
2985 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2986 &BTRFS_I(inode)->runtime_flags))
2987 reserve = 1;
2988 spin_unlock(&root->orphan_lock);
2989
2990 /* grab metadata reservation from transaction handle */
2991 if (reserve) {
2992 ret = btrfs_orphan_reserve_metadata(trans, inode);
2993 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2994 }
2995
2996 /* insert an orphan item to track this unlinked/truncated file */
2997 if (insert >= 1) {
2998 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2999 if (ret && ret != -EEXIST) {
3000 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3001 &BTRFS_I(inode)->runtime_flags);
3002 btrfs_abort_transaction(trans, root, ret);
3003 return ret;
3004 }
3005 ret = 0;
3006 }
3007
3008 /* insert an orphan item to track subvolume contains orphan files */
3009 if (insert >= 2) {
3010 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3011 root->root_key.objectid);
3012 if (ret && ret != -EEXIST) {
3013 btrfs_abort_transaction(trans, root, ret);
3014 return ret;
3015 }
3016 }
3017 return 0;
3018 }
3019
3020 /*
3021 * We have done the truncate/delete so we can go ahead and remove the orphan
3022 * item for this particular inode.
3023 */
3024 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
3025 {
3026 struct btrfs_root *root = BTRFS_I(inode)->root;
3027 int delete_item = 0;
3028 int release_rsv = 0;
3029 int ret = 0;
3030
3031 spin_lock(&root->orphan_lock);
3032 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3033 &BTRFS_I(inode)->runtime_flags))
3034 delete_item = 1;
3035
3036 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3037 &BTRFS_I(inode)->runtime_flags))
3038 release_rsv = 1;
3039 spin_unlock(&root->orphan_lock);
3040
3041 if (trans && delete_item) {
3042 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3043 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3044 }
3045
3046 if (release_rsv) {
3047 btrfs_orphan_release_metadata(inode);
3048 atomic_dec(&root->orphan_inodes);
3049 }
3050
3051 return 0;
3052 }
3053
3054 /*
3055 * this cleans up any orphans that may be left on the list from the last use
3056 * of this root.
3057 */
3058 int btrfs_orphan_cleanup(struct btrfs_root *root)
3059 {
3060 struct btrfs_path *path;
3061 struct extent_buffer *leaf;
3062 struct btrfs_key key, found_key;
3063 struct btrfs_trans_handle *trans;
3064 struct inode *inode;
3065 u64 last_objectid = 0;
3066 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3067
3068 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3069 return 0;
3070
3071 path = btrfs_alloc_path();
3072 if (!path) {
3073 ret = -ENOMEM;
3074 goto out;
3075 }
3076 path->reada = -1;
3077
3078 key.objectid = BTRFS_ORPHAN_OBJECTID;
3079 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3080 key.offset = (u64)-1;
3081
3082 while (1) {
3083 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3084 if (ret < 0)
3085 goto out;
3086
3087 /*
3088 * if ret == 0 means we found what we were searching for, which
3089 * is weird, but possible, so only screw with path if we didn't
3090 * find the key and see if we have stuff that matches
3091 */
3092 if (ret > 0) {
3093 ret = 0;
3094 if (path->slots[0] == 0)
3095 break;
3096 path->slots[0]--;
3097 }
3098
3099 /* pull out the item */
3100 leaf = path->nodes[0];
3101 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3102
3103 /* make sure the item matches what we want */
3104 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3105 break;
3106 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3107 break;
3108
3109 /* release the path since we're done with it */
3110 btrfs_release_path(path);
3111
3112 /*
3113 * this is where we are basically btrfs_lookup, without the
3114 * crossing root thing. we store the inode number in the
3115 * offset of the orphan item.
3116 */
3117
3118 if (found_key.offset == last_objectid) {
3119 btrfs_err(root->fs_info,
3120 "Error removing orphan entry, stopping orphan cleanup");
3121 ret = -EINVAL;
3122 goto out;
3123 }
3124
3125 last_objectid = found_key.offset;
3126
3127 found_key.objectid = found_key.offset;
3128 found_key.type = BTRFS_INODE_ITEM_KEY;
3129 found_key.offset = 0;
3130 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3131 ret = PTR_RET(inode);
3132 if (ret && ret != -ESTALE)
3133 goto out;
3134
3135 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3136 struct btrfs_root *dead_root;
3137 struct btrfs_fs_info *fs_info = root->fs_info;
3138 int is_dead_root = 0;
3139
3140 /*
3141 * this is an orphan in the tree root. Currently these
3142 * could come from 2 sources:
3143 * a) a snapshot deletion in progress
3144 * b) a free space cache inode
3145 * We need to distinguish those two, as the snapshot
3146 * orphan must not get deleted.
3147 * find_dead_roots already ran before us, so if this
3148 * is a snapshot deletion, we should find the root
3149 * in the dead_roots list
3150 */
3151 spin_lock(&fs_info->trans_lock);
3152 list_for_each_entry(dead_root, &fs_info->dead_roots,
3153 root_list) {
3154 if (dead_root->root_key.objectid ==
3155 found_key.objectid) {
3156 is_dead_root = 1;
3157 break;
3158 }
3159 }
3160 spin_unlock(&fs_info->trans_lock);
3161 if (is_dead_root) {
3162 /* prevent this orphan from being found again */
3163 key.offset = found_key.objectid - 1;
3164 continue;
3165 }
3166 }
3167 /*
3168 * Inode is already gone but the orphan item is still there,
3169 * kill the orphan item.
3170 */
3171 if (ret == -ESTALE) {
3172 trans = btrfs_start_transaction(root, 1);
3173 if (IS_ERR(trans)) {
3174 ret = PTR_ERR(trans);
3175 goto out;
3176 }
3177 btrfs_debug(root->fs_info, "auto deleting %Lu",
3178 found_key.objectid);
3179 ret = btrfs_del_orphan_item(trans, root,
3180 found_key.objectid);
3181 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3182 btrfs_end_transaction(trans, root);
3183 continue;
3184 }
3185
3186 /*
3187 * add this inode to the orphan list so btrfs_orphan_del does
3188 * the proper thing when we hit it
3189 */
3190 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3191 &BTRFS_I(inode)->runtime_flags);
3192 atomic_inc(&root->orphan_inodes);
3193
3194 /* if we have links, this was a truncate, lets do that */
3195 if (inode->i_nlink) {
3196 if (!S_ISREG(inode->i_mode)) {
3197 WARN_ON(1);
3198 iput(inode);
3199 continue;
3200 }
3201 nr_truncate++;
3202
3203 /* 1 for the orphan item deletion. */
3204 trans = btrfs_start_transaction(root, 1);
3205 if (IS_ERR(trans)) {
3206 ret = PTR_ERR(trans);
3207 goto out;
3208 }
3209 ret = btrfs_orphan_add(trans, inode);
3210 btrfs_end_transaction(trans, root);
3211 if (ret)
3212 goto out;
3213
3214 ret = btrfs_truncate(inode);
3215 if (ret)
3216 btrfs_orphan_del(NULL, inode);
3217 } else {
3218 nr_unlink++;
3219 }
3220
3221 /* this will do delete_inode and everything for us */
3222 iput(inode);
3223 if (ret)
3224 goto out;
3225 }
3226 /* release the path since we're done with it */
3227 btrfs_release_path(path);
3228
3229 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3230
3231 if (root->orphan_block_rsv)
3232 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3233 (u64)-1);
3234
3235 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3236 trans = btrfs_join_transaction(root);
3237 if (!IS_ERR(trans))
3238 btrfs_end_transaction(trans, root);
3239 }
3240
3241 if (nr_unlink)
3242 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3243 if (nr_truncate)
3244 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3245
3246 out:
3247 if (ret)
3248 btrfs_crit(root->fs_info,
3249 "could not do orphan cleanup %d", ret);
3250 btrfs_free_path(path);
3251 return ret;
3252 }
3253
3254 /*
3255 * very simple check to peek ahead in the leaf looking for xattrs. If we
3256 * don't find any xattrs, we know there can't be any acls.
3257 *
3258 * slot is the slot the inode is in, objectid is the objectid of the inode
3259 */
3260 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3261 int slot, u64 objectid)
3262 {
3263 u32 nritems = btrfs_header_nritems(leaf);
3264 struct btrfs_key found_key;
3265 int scanned = 0;
3266
3267 slot++;
3268 while (slot < nritems) {
3269 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3270
3271 /* we found a different objectid, there must not be acls */
3272 if (found_key.objectid != objectid)
3273 return 0;
3274
3275 /* we found an xattr, assume we've got an acl */
3276 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
3277 return 1;
3278
3279 /*
3280 * we found a key greater than an xattr key, there can't
3281 * be any acls later on
3282 */
3283 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3284 return 0;
3285
3286 slot++;
3287 scanned++;
3288
3289 /*
3290 * it goes inode, inode backrefs, xattrs, extents,
3291 * so if there are a ton of hard links to an inode there can
3292 * be a lot of backrefs. Don't waste time searching too hard,
3293 * this is just an optimization
3294 */
3295 if (scanned >= 8)
3296 break;
3297 }
3298 /* we hit the end of the leaf before we found an xattr or
3299 * something larger than an xattr. We have to assume the inode
3300 * has acls
3301 */
3302 return 1;
3303 }
3304
3305 /*
3306 * read an inode from the btree into the in-memory inode
3307 */
3308 static void btrfs_read_locked_inode(struct inode *inode)
3309 {
3310 struct btrfs_path *path;
3311 struct extent_buffer *leaf;
3312 struct btrfs_inode_item *inode_item;
3313 struct btrfs_timespec *tspec;
3314 struct btrfs_root *root = BTRFS_I(inode)->root;
3315 struct btrfs_key location;
3316 int maybe_acls;
3317 u32 rdev;
3318 int ret;
3319 bool filled = false;
3320
3321 ret = btrfs_fill_inode(inode, &rdev);
3322 if (!ret)
3323 filled = true;
3324
3325 path = btrfs_alloc_path();
3326 if (!path)
3327 goto make_bad;
3328
3329 path->leave_spinning = 1;
3330 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3331
3332 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3333 if (ret)
3334 goto make_bad;
3335
3336 leaf = path->nodes[0];
3337
3338 if (filled)
3339 goto cache_acl;
3340
3341 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3342 struct btrfs_inode_item);
3343 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3344 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3345 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3346 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3347 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3348
3349 tspec = btrfs_inode_atime(inode_item);
3350 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3351 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3352
3353 tspec = btrfs_inode_mtime(inode_item);
3354 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3355 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3356
3357 tspec = btrfs_inode_ctime(inode_item);
3358 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3359 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3360
3361 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3362 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3363 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3364
3365 /*
3366 * If we were modified in the current generation and evicted from memory
3367 * and then re-read we need to do a full sync since we don't have any
3368 * idea about which extents were modified before we were evicted from
3369 * cache.
3370 */
3371 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3372 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3373 &BTRFS_I(inode)->runtime_flags);
3374
3375 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3376 inode->i_generation = BTRFS_I(inode)->generation;
3377 inode->i_rdev = 0;
3378 rdev = btrfs_inode_rdev(leaf, inode_item);
3379
3380 BTRFS_I(inode)->index_cnt = (u64)-1;
3381 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3382 cache_acl:
3383 /*
3384 * try to precache a NULL acl entry for files that don't have
3385 * any xattrs or acls
3386 */
3387 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3388 btrfs_ino(inode));
3389 if (!maybe_acls)
3390 cache_no_acl(inode);
3391
3392 btrfs_free_path(path);
3393
3394 switch (inode->i_mode & S_IFMT) {
3395 case S_IFREG:
3396 inode->i_mapping->a_ops = &btrfs_aops;
3397 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3398 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3399 inode->i_fop = &btrfs_file_operations;
3400 inode->i_op = &btrfs_file_inode_operations;
3401 break;
3402 case S_IFDIR:
3403 inode->i_fop = &btrfs_dir_file_operations;
3404 if (root == root->fs_info->tree_root)
3405 inode->i_op = &btrfs_dir_ro_inode_operations;
3406 else
3407 inode->i_op = &btrfs_dir_inode_operations;
3408 break;
3409 case S_IFLNK:
3410 inode->i_op = &btrfs_symlink_inode_operations;
3411 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3412 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3413 break;
3414 default:
3415 inode->i_op = &btrfs_special_inode_operations;
3416 init_special_inode(inode, inode->i_mode, rdev);
3417 break;
3418 }
3419
3420 btrfs_update_iflags(inode);
3421 return;
3422
3423 make_bad:
3424 btrfs_free_path(path);
3425 make_bad_inode(inode);
3426 }
3427
3428 /*
3429 * given a leaf and an inode, copy the inode fields into the leaf
3430 */
3431 static void fill_inode_item(struct btrfs_trans_handle *trans,
3432 struct extent_buffer *leaf,
3433 struct btrfs_inode_item *item,
3434 struct inode *inode)
3435 {
3436 struct btrfs_map_token token;
3437
3438 btrfs_init_map_token(&token);
3439
3440 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3441 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3442 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3443 &token);
3444 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3445 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3446
3447 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3448 inode->i_atime.tv_sec, &token);
3449 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3450 inode->i_atime.tv_nsec, &token);
3451
3452 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3453 inode->i_mtime.tv_sec, &token);
3454 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3455 inode->i_mtime.tv_nsec, &token);
3456
3457 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3458 inode->i_ctime.tv_sec, &token);
3459 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3460 inode->i_ctime.tv_nsec, &token);
3461
3462 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3463 &token);
3464 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3465 &token);
3466 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3467 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3468 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3469 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3470 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3471 }
3472
3473 /*
3474 * copy everything in the in-memory inode into the btree.
3475 */
3476 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3477 struct btrfs_root *root, struct inode *inode)
3478 {
3479 struct btrfs_inode_item *inode_item;
3480 struct btrfs_path *path;
3481 struct extent_buffer *leaf;
3482 int ret;
3483
3484 path = btrfs_alloc_path();
3485 if (!path)
3486 return -ENOMEM;
3487
3488 path->leave_spinning = 1;
3489 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3490 1);
3491 if (ret) {
3492 if (ret > 0)
3493 ret = -ENOENT;
3494 goto failed;
3495 }
3496
3497 btrfs_unlock_up_safe(path, 1);
3498 leaf = path->nodes[0];
3499 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3500 struct btrfs_inode_item);
3501
3502 fill_inode_item(trans, leaf, inode_item, inode);
3503 btrfs_mark_buffer_dirty(leaf);
3504 btrfs_set_inode_last_trans(trans, inode);
3505 ret = 0;
3506 failed:
3507 btrfs_free_path(path);
3508 return ret;
3509 }
3510
3511 /*
3512 * copy everything in the in-memory inode into the btree.
3513 */
3514 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3515 struct btrfs_root *root, struct inode *inode)
3516 {
3517 int ret;
3518
3519 /*
3520 * If the inode is a free space inode, we can deadlock during commit
3521 * if we put it into the delayed code.
3522 *
3523 * The data relocation inode should also be directly updated
3524 * without delay
3525 */
3526 if (!btrfs_is_free_space_inode(inode)
3527 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3528 btrfs_update_root_times(trans, root);
3529
3530 ret = btrfs_delayed_update_inode(trans, root, inode);
3531 if (!ret)
3532 btrfs_set_inode_last_trans(trans, inode);
3533 return ret;
3534 }
3535
3536 return btrfs_update_inode_item(trans, root, inode);
3537 }
3538
3539 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3540 struct btrfs_root *root,
3541 struct inode *inode)
3542 {
3543 int ret;
3544
3545 ret = btrfs_update_inode(trans, root, inode);
3546 if (ret == -ENOSPC)
3547 return btrfs_update_inode_item(trans, root, inode);
3548 return ret;
3549 }
3550
3551 /*
3552 * unlink helper that gets used here in inode.c and in the tree logging
3553 * recovery code. It remove a link in a directory with a given name, and
3554 * also drops the back refs in the inode to the directory
3555 */
3556 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3557 struct btrfs_root *root,
3558 struct inode *dir, struct inode *inode,
3559 const char *name, int name_len)
3560 {
3561 struct btrfs_path *path;
3562 int ret = 0;
3563 struct extent_buffer *leaf;
3564 struct btrfs_dir_item *di;
3565 struct btrfs_key key;
3566 u64 index;
3567 u64 ino = btrfs_ino(inode);
3568 u64 dir_ino = btrfs_ino(dir);
3569
3570 path = btrfs_alloc_path();
3571 if (!path) {
3572 ret = -ENOMEM;
3573 goto out;
3574 }
3575
3576 path->leave_spinning = 1;
3577 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3578 name, name_len, -1);
3579 if (IS_ERR(di)) {
3580 ret = PTR_ERR(di);
3581 goto err;
3582 }
3583 if (!di) {
3584 ret = -ENOENT;
3585 goto err;
3586 }
3587 leaf = path->nodes[0];
3588 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3589 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3590 if (ret)
3591 goto err;
3592 btrfs_release_path(path);
3593
3594 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3595 dir_ino, &index);
3596 if (ret) {
3597 btrfs_info(root->fs_info,
3598 "failed to delete reference to %.*s, inode %llu parent %llu",
3599 name_len, name,
3600 (unsigned long long)ino, (unsigned long long)dir_ino);
3601 btrfs_abort_transaction(trans, root, ret);
3602 goto err;
3603 }
3604
3605 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3606 if (ret) {
3607 btrfs_abort_transaction(trans, root, ret);
3608 goto err;
3609 }
3610
3611 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3612 inode, dir_ino);
3613 if (ret != 0 && ret != -ENOENT) {
3614 btrfs_abort_transaction(trans, root, ret);
3615 goto err;
3616 }
3617
3618 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3619 dir, index);
3620 if (ret == -ENOENT)
3621 ret = 0;
3622 err:
3623 btrfs_free_path(path);
3624 if (ret)
3625 goto out;
3626
3627 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3628 inode_inc_iversion(inode);
3629 inode_inc_iversion(dir);
3630 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3631 ret = btrfs_update_inode(trans, root, dir);
3632 out:
3633 return ret;
3634 }
3635
3636 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3637 struct btrfs_root *root,
3638 struct inode *dir, struct inode *inode,
3639 const char *name, int name_len)
3640 {
3641 int ret;
3642 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3643 if (!ret) {
3644 btrfs_drop_nlink(inode);
3645 ret = btrfs_update_inode(trans, root, inode);
3646 }
3647 return ret;
3648 }
3649
3650
3651 /* helper to check if there is any shared block in the path */
3652 static int check_path_shared(struct btrfs_root *root,
3653 struct btrfs_path *path)
3654 {
3655 struct extent_buffer *eb;
3656 int level;
3657 u64 refs = 1;
3658
3659 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
3660 int ret;
3661
3662 if (!path->nodes[level])
3663 break;
3664 eb = path->nodes[level];
3665 if (!btrfs_block_can_be_shared(root, eb))
3666 continue;
3667 ret = btrfs_lookup_extent_info(NULL, root, eb->start, level, 1,
3668 &refs, NULL);
3669 if (refs > 1)
3670 return 1;
3671 }
3672 return 0;
3673 }
3674
3675 /*
3676 * helper to start transaction for unlink and rmdir.
3677 *
3678 * unlink and rmdir are special in btrfs, they do not always free space.
3679 * so in enospc case, we should make sure they will free space before
3680 * allowing them to use the global metadata reservation.
3681 */
3682 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
3683 struct dentry *dentry)
3684 {
3685 struct btrfs_trans_handle *trans;
3686 struct btrfs_root *root = BTRFS_I(dir)->root;
3687 struct btrfs_path *path;
3688 struct btrfs_dir_item *di;
3689 struct inode *inode = dentry->d_inode;
3690 u64 index;
3691 int check_link = 1;
3692 int err = -ENOSPC;
3693 int ret;
3694 u64 ino = btrfs_ino(inode);
3695 u64 dir_ino = btrfs_ino(dir);
3696
3697 /*
3698 * 1 for the possible orphan item
3699 * 1 for the dir item
3700 * 1 for the dir index
3701 * 1 for the inode ref
3702 * 1 for the inode
3703 */
3704 trans = btrfs_start_transaction(root, 5);
3705 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3706 return trans;
3707
3708 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
3709 return ERR_PTR(-ENOSPC);
3710
3711 /* check if there is someone else holds reference */
3712 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
3713 return ERR_PTR(-ENOSPC);
3714
3715 if (atomic_read(&inode->i_count) > 2)
3716 return ERR_PTR(-ENOSPC);
3717
3718 if (xchg(&root->fs_info->enospc_unlink, 1))
3719 return ERR_PTR(-ENOSPC);
3720
3721 path = btrfs_alloc_path();
3722 if (!path) {
3723 root->fs_info->enospc_unlink = 0;
3724 return ERR_PTR(-ENOMEM);
3725 }
3726
3727 /* 1 for the orphan item */
3728 trans = btrfs_start_transaction(root, 1);
3729 if (IS_ERR(trans)) {
3730 btrfs_free_path(path);
3731 root->fs_info->enospc_unlink = 0;
3732 return trans;
3733 }
3734
3735 path->skip_locking = 1;
3736 path->search_commit_root = 1;
3737
3738 ret = btrfs_lookup_inode(trans, root, path,
3739 &BTRFS_I(dir)->location, 0);
3740 if (ret < 0) {
3741 err = ret;
3742 goto out;
3743 }
3744 if (ret == 0) {
3745 if (check_path_shared(root, path))
3746 goto out;
3747 } else {
3748 check_link = 0;
3749 }
3750 btrfs_release_path(path);
3751
3752 ret = btrfs_lookup_inode(trans, root, path,
3753 &BTRFS_I(inode)->location, 0);
3754 if (ret < 0) {
3755 err = ret;
3756 goto out;
3757 }
3758 if (ret == 0) {
3759 if (check_path_shared(root, path))
3760 goto out;
3761 } else {
3762 check_link = 0;
3763 }
3764 btrfs_release_path(path);
3765
3766 if (ret == 0 && S_ISREG(inode->i_mode)) {
3767 ret = btrfs_lookup_file_extent(trans, root, path,
3768 ino, (u64)-1, 0);
3769 if (ret < 0) {
3770 err = ret;
3771 goto out;
3772 }
3773 BUG_ON(ret == 0); /* Corruption */
3774 if (check_path_shared(root, path))
3775 goto out;
3776 btrfs_release_path(path);
3777 }
3778
3779 if (!check_link) {
3780 err = 0;
3781 goto out;
3782 }
3783
3784 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3785 dentry->d_name.name, dentry->d_name.len, 0);
3786 if (IS_ERR(di)) {
3787 err = PTR_ERR(di);
3788 goto out;
3789 }
3790 if (di) {
3791 if (check_path_shared(root, path))
3792 goto out;
3793 } else {
3794 err = 0;
3795 goto out;
3796 }
3797 btrfs_release_path(path);
3798
3799 ret = btrfs_get_inode_ref_index(trans, root, path, dentry->d_name.name,
3800 dentry->d_name.len, ino, dir_ino, 0,
3801 &index);
3802 if (ret) {
3803 err = ret;
3804 goto out;
3805 }
3806
3807 if (check_path_shared(root, path))
3808 goto out;
3809
3810 btrfs_release_path(path);
3811
3812 /*
3813 * This is a commit root search, if we can lookup inode item and other
3814 * relative items in the commit root, it means the transaction of
3815 * dir/file creation has been committed, and the dir index item that we
3816 * delay to insert has also been inserted into the commit root. So
3817 * we needn't worry about the delayed insertion of the dir index item
3818 * here.
3819 */
3820 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
3821 dentry->d_name.name, dentry->d_name.len, 0);
3822 if (IS_ERR(di)) {
3823 err = PTR_ERR(di);
3824 goto out;
3825 }
3826 BUG_ON(ret == -ENOENT);
3827 if (check_path_shared(root, path))
3828 goto out;
3829
3830 err = 0;
3831 out:
3832 btrfs_free_path(path);
3833 /* Migrate the orphan reservation over */
3834 if (!err)
3835 err = btrfs_block_rsv_migrate(trans->block_rsv,
3836 &root->fs_info->global_block_rsv,
3837 trans->bytes_reserved);
3838
3839 if (err) {
3840 btrfs_end_transaction(trans, root);
3841 root->fs_info->enospc_unlink = 0;
3842 return ERR_PTR(err);
3843 }
3844
3845 trans->block_rsv = &root->fs_info->global_block_rsv;
3846 return trans;
3847 }
3848
3849 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3850 struct btrfs_root *root)
3851 {
3852 if (trans->block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL) {
3853 btrfs_block_rsv_release(root, trans->block_rsv,
3854 trans->bytes_reserved);
3855 trans->block_rsv = &root->fs_info->trans_block_rsv;
3856 BUG_ON(!root->fs_info->enospc_unlink);
3857 root->fs_info->enospc_unlink = 0;
3858 }
3859 btrfs_end_transaction(trans, root);
3860 }
3861
3862 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3863 {
3864 struct btrfs_root *root = BTRFS_I(dir)->root;
3865 struct btrfs_trans_handle *trans;
3866 struct inode *inode = dentry->d_inode;
3867 int ret;
3868
3869 trans = __unlink_start_trans(dir, dentry);
3870 if (IS_ERR(trans))
3871 return PTR_ERR(trans);
3872
3873 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3874
3875 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3876 dentry->d_name.name, dentry->d_name.len);
3877 if (ret)
3878 goto out;
3879
3880 if (inode->i_nlink == 0) {
3881 ret = btrfs_orphan_add(trans, inode);
3882 if (ret)
3883 goto out;
3884 }
3885
3886 out:
3887 __unlink_end_trans(trans, root);
3888 btrfs_btree_balance_dirty(root);
3889 return ret;
3890 }
3891
3892 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3893 struct btrfs_root *root,
3894 struct inode *dir, u64 objectid,
3895 const char *name, int name_len)
3896 {
3897 struct btrfs_path *path;
3898 struct extent_buffer *leaf;
3899 struct btrfs_dir_item *di;
3900 struct btrfs_key key;
3901 u64 index;
3902 int ret;
3903 u64 dir_ino = btrfs_ino(dir);
3904
3905 path = btrfs_alloc_path();
3906 if (!path)
3907 return -ENOMEM;
3908
3909 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3910 name, name_len, -1);
3911 if (IS_ERR_OR_NULL(di)) {
3912 if (!di)
3913 ret = -ENOENT;
3914 else
3915 ret = PTR_ERR(di);
3916 goto out;
3917 }
3918
3919 leaf = path->nodes[0];
3920 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3921 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3922 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3923 if (ret) {
3924 btrfs_abort_transaction(trans, root, ret);
3925 goto out;
3926 }
3927 btrfs_release_path(path);
3928
3929 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3930 objectid, root->root_key.objectid,
3931 dir_ino, &index, name, name_len);
3932 if (ret < 0) {
3933 if (ret != -ENOENT) {
3934 btrfs_abort_transaction(trans, root, ret);
3935 goto out;
3936 }
3937 di = btrfs_search_dir_index_item(root, path, dir_ino,
3938 name, name_len);
3939 if (IS_ERR_OR_NULL(di)) {
3940 if (!di)
3941 ret = -ENOENT;
3942 else
3943 ret = PTR_ERR(di);
3944 btrfs_abort_transaction(trans, root, ret);
3945 goto out;
3946 }
3947
3948 leaf = path->nodes[0];
3949 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3950 btrfs_release_path(path);
3951 index = key.offset;
3952 }
3953 btrfs_release_path(path);
3954
3955 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3956 if (ret) {
3957 btrfs_abort_transaction(trans, root, ret);
3958 goto out;
3959 }
3960
3961 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3962 inode_inc_iversion(dir);
3963 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3964 ret = btrfs_update_inode_fallback(trans, root, dir);
3965 if (ret)
3966 btrfs_abort_transaction(trans, root, ret);
3967 out:
3968 btrfs_free_path(path);
3969 return ret;
3970 }
3971
3972 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3973 {
3974 struct inode *inode = dentry->d_inode;
3975 int err = 0;
3976 struct btrfs_root *root = BTRFS_I(dir)->root;
3977 struct btrfs_trans_handle *trans;
3978
3979 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3980 return -ENOTEMPTY;
3981 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3982 return -EPERM;
3983
3984 trans = __unlink_start_trans(dir, dentry);
3985 if (IS_ERR(trans))
3986 return PTR_ERR(trans);
3987
3988 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3989 err = btrfs_unlink_subvol(trans, root, dir,
3990 BTRFS_I(inode)->location.objectid,
3991 dentry->d_name.name,
3992 dentry->d_name.len);
3993 goto out;
3994 }
3995
3996 err = btrfs_orphan_add(trans, inode);
3997 if (err)
3998 goto out;
3999
4000 /* now the directory is empty */
4001 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4002 dentry->d_name.name, dentry->d_name.len);
4003 if (!err)
4004 btrfs_i_size_write(inode, 0);
4005 out:
4006 __unlink_end_trans(trans, root);
4007 btrfs_btree_balance_dirty(root);
4008
4009 return err;
4010 }
4011
4012 /*
4013 * this can truncate away extent items, csum items and directory items.
4014 * It starts at a high offset and removes keys until it can't find
4015 * any higher than new_size
4016 *
4017 * csum items that cross the new i_size are truncated to the new size
4018 * as well.
4019 *
4020 * min_type is the minimum key type to truncate down to. If set to 0, this
4021 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4022 */
4023 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4024 struct btrfs_root *root,
4025 struct inode *inode,
4026 u64 new_size, u32 min_type)
4027 {
4028 struct btrfs_path *path;
4029 struct extent_buffer *leaf;
4030 struct btrfs_file_extent_item *fi;
4031 struct btrfs_key key;
4032 struct btrfs_key found_key;
4033 u64 extent_start = 0;
4034 u64 extent_num_bytes = 0;
4035 u64 extent_offset = 0;
4036 u64 item_end = 0;
4037 u32 found_type = (u8)-1;
4038 int found_extent;
4039 int del_item;
4040 int pending_del_nr = 0;
4041 int pending_del_slot = 0;
4042 int extent_type = -1;
4043 int ret;
4044 int err = 0;
4045 u64 ino = btrfs_ino(inode);
4046
4047 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4048
4049 path = btrfs_alloc_path();
4050 if (!path)
4051 return -ENOMEM;
4052 path->reada = -1;
4053
4054 /*
4055 * We want to drop from the next block forward in case this new size is
4056 * not block aligned since we will be keeping the last block of the
4057 * extent just the way it is.
4058 */
4059 if (root->ref_cows || root == root->fs_info->tree_root)
4060 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4061 root->sectorsize), (u64)-1, 0);
4062
4063 /*
4064 * This function is also used to drop the items in the log tree before
4065 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4066 * it is used to drop the loged items. So we shouldn't kill the delayed
4067 * items.
4068 */
4069 if (min_type == 0 && root == BTRFS_I(inode)->root)
4070 btrfs_kill_delayed_inode_items(inode);
4071
4072 key.objectid = ino;
4073 key.offset = (u64)-1;
4074 key.type = (u8)-1;
4075
4076 search_again:
4077 path->leave_spinning = 1;
4078 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4079 if (ret < 0) {
4080 err = ret;
4081 goto out;
4082 }
4083
4084 if (ret > 0) {
4085 /* there are no items in the tree for us to truncate, we're
4086 * done
4087 */
4088 if (path->slots[0] == 0)
4089 goto out;
4090 path->slots[0]--;
4091 }
4092
4093 while (1) {
4094 fi = NULL;
4095 leaf = path->nodes[0];
4096 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4097 found_type = btrfs_key_type(&found_key);
4098
4099 if (found_key.objectid != ino)
4100 break;
4101
4102 if (found_type < min_type)
4103 break;
4104
4105 item_end = found_key.offset;
4106 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4107 fi = btrfs_item_ptr(leaf, path->slots[0],
4108 struct btrfs_file_extent_item);
4109 extent_type = btrfs_file_extent_type(leaf, fi);
4110 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4111 item_end +=
4112 btrfs_file_extent_num_bytes(leaf, fi);
4113 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4114 item_end += btrfs_file_extent_inline_len(leaf,
4115 fi);
4116 }
4117 item_end--;
4118 }
4119 if (found_type > min_type) {
4120 del_item = 1;
4121 } else {
4122 if (item_end < new_size)
4123 break;
4124 if (found_key.offset >= new_size)
4125 del_item = 1;
4126 else
4127 del_item = 0;
4128 }
4129 found_extent = 0;
4130 /* FIXME, shrink the extent if the ref count is only 1 */
4131 if (found_type != BTRFS_EXTENT_DATA_KEY)
4132 goto delete;
4133
4134 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4135 u64 num_dec;
4136 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4137 if (!del_item) {
4138 u64 orig_num_bytes =
4139 btrfs_file_extent_num_bytes(leaf, fi);
4140 extent_num_bytes = ALIGN(new_size -
4141 found_key.offset,
4142 root->sectorsize);
4143 btrfs_set_file_extent_num_bytes(leaf, fi,
4144 extent_num_bytes);
4145 num_dec = (orig_num_bytes -
4146 extent_num_bytes);
4147 if (root->ref_cows && extent_start != 0)
4148 inode_sub_bytes(inode, num_dec);
4149 btrfs_mark_buffer_dirty(leaf);
4150 } else {
4151 extent_num_bytes =
4152 btrfs_file_extent_disk_num_bytes(leaf,
4153 fi);
4154 extent_offset = found_key.offset -
4155 btrfs_file_extent_offset(leaf, fi);
4156
4157 /* FIXME blocksize != 4096 */
4158 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4159 if (extent_start != 0) {
4160 found_extent = 1;
4161 if (root->ref_cows)
4162 inode_sub_bytes(inode, num_dec);
4163 }
4164 }
4165 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4166 /*
4167 * we can't truncate inline items that have had
4168 * special encodings
4169 */
4170 if (!del_item &&
4171 btrfs_file_extent_compression(leaf, fi) == 0 &&
4172 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4173 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4174 u32 size = new_size - found_key.offset;
4175
4176 if (root->ref_cows) {
4177 inode_sub_bytes(inode, item_end + 1 -
4178 new_size);
4179 }
4180 size =
4181 btrfs_file_extent_calc_inline_size(size);
4182 btrfs_truncate_item(trans, root, path,
4183 size, 1);
4184 } else if (root->ref_cows) {
4185 inode_sub_bytes(inode, item_end + 1 -
4186 found_key.offset);
4187 }
4188 }
4189 delete:
4190 if (del_item) {
4191 if (!pending_del_nr) {
4192 /* no pending yet, add ourselves */
4193 pending_del_slot = path->slots[0];
4194 pending_del_nr = 1;
4195 } else if (pending_del_nr &&
4196 path->slots[0] + 1 == pending_del_slot) {
4197 /* hop on the pending chunk */
4198 pending_del_nr++;
4199 pending_del_slot = path->slots[0];
4200 } else {
4201 BUG();
4202 }
4203 } else {
4204 break;
4205 }
4206 if (found_extent && (root->ref_cows ||
4207 root == root->fs_info->tree_root)) {
4208 btrfs_set_path_blocking(path);
4209 ret = btrfs_free_extent(trans, root, extent_start,
4210 extent_num_bytes, 0,
4211 btrfs_header_owner(leaf),
4212 ino, extent_offset, 0);
4213 BUG_ON(ret);
4214 }
4215
4216 if (found_type == BTRFS_INODE_ITEM_KEY)
4217 break;
4218
4219 if (path->slots[0] == 0 ||
4220 path->slots[0] != pending_del_slot) {
4221 if (pending_del_nr) {
4222 ret = btrfs_del_items(trans, root, path,
4223 pending_del_slot,
4224 pending_del_nr);
4225 if (ret) {
4226 btrfs_abort_transaction(trans,
4227 root, ret);
4228 goto error;
4229 }
4230 pending_del_nr = 0;
4231 }
4232 btrfs_release_path(path);
4233 goto search_again;
4234 } else {
4235 path->slots[0]--;
4236 }
4237 }
4238 out:
4239 if (pending_del_nr) {
4240 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4241 pending_del_nr);
4242 if (ret)
4243 btrfs_abort_transaction(trans, root, ret);
4244 }
4245 error:
4246 btrfs_free_path(path);
4247 return err;
4248 }
4249
4250 /*
4251 * btrfs_truncate_page - read, zero a chunk and write a page
4252 * @inode - inode that we're zeroing
4253 * @from - the offset to start zeroing
4254 * @len - the length to zero, 0 to zero the entire range respective to the
4255 * offset
4256 * @front - zero up to the offset instead of from the offset on
4257 *
4258 * This will find the page for the "from" offset and cow the page and zero the
4259 * part we want to zero. This is used with truncate and hole punching.
4260 */
4261 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4262 int front)
4263 {
4264 struct address_space *mapping = inode->i_mapping;
4265 struct btrfs_root *root = BTRFS_I(inode)->root;
4266 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4267 struct btrfs_ordered_extent *ordered;
4268 struct extent_state *cached_state = NULL;
4269 char *kaddr;
4270 u32 blocksize = root->sectorsize;
4271 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4272 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4273 struct page *page;
4274 gfp_t mask = btrfs_alloc_write_mask(mapping);
4275 int ret = 0;
4276 u64 page_start;
4277 u64 page_end;
4278
4279 if ((offset & (blocksize - 1)) == 0 &&
4280 (!len || ((len & (blocksize - 1)) == 0)))
4281 goto out;
4282 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4283 if (ret)
4284 goto out;
4285
4286 again:
4287 page = find_or_create_page(mapping, index, mask);
4288 if (!page) {
4289 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4290 ret = -ENOMEM;
4291 goto out;
4292 }
4293
4294 page_start = page_offset(page);
4295 page_end = page_start + PAGE_CACHE_SIZE - 1;
4296
4297 if (!PageUptodate(page)) {
4298 ret = btrfs_readpage(NULL, page);
4299 lock_page(page);
4300 if (page->mapping != mapping) {
4301 unlock_page(page);
4302 page_cache_release(page);
4303 goto again;
4304 }
4305 if (!PageUptodate(page)) {
4306 ret = -EIO;
4307 goto out_unlock;
4308 }
4309 }
4310 wait_on_page_writeback(page);
4311
4312 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4313 set_page_extent_mapped(page);
4314
4315 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4316 if (ordered) {
4317 unlock_extent_cached(io_tree, page_start, page_end,
4318 &cached_state, GFP_NOFS);
4319 unlock_page(page);
4320 page_cache_release(page);
4321 btrfs_start_ordered_extent(inode, ordered, 1);
4322 btrfs_put_ordered_extent(ordered);
4323 goto again;
4324 }
4325
4326 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4327 EXTENT_DIRTY | EXTENT_DELALLOC |
4328 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4329 0, 0, &cached_state, GFP_NOFS);
4330
4331 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4332 &cached_state);
4333 if (ret) {
4334 unlock_extent_cached(io_tree, page_start, page_end,
4335 &cached_state, GFP_NOFS);
4336 goto out_unlock;
4337 }
4338
4339 if (offset != PAGE_CACHE_SIZE) {
4340 if (!len)
4341 len = PAGE_CACHE_SIZE - offset;
4342 kaddr = kmap(page);
4343 if (front)
4344 memset(kaddr, 0, offset);
4345 else
4346 memset(kaddr + offset, 0, len);
4347 flush_dcache_page(page);
4348 kunmap(page);
4349 }
4350 ClearPageChecked(page);
4351 set_page_dirty(page);
4352 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4353 GFP_NOFS);
4354
4355 out_unlock:
4356 if (ret)
4357 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4358 unlock_page(page);
4359 page_cache_release(page);
4360 out:
4361 return ret;
4362 }
4363
4364 /*
4365 * This function puts in dummy file extents for the area we're creating a hole
4366 * for. So if we are truncating this file to a larger size we need to insert
4367 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4368 * the range between oldsize and size
4369 */
4370 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4371 {
4372 struct btrfs_trans_handle *trans;
4373 struct btrfs_root *root = BTRFS_I(inode)->root;
4374 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4375 struct extent_map *em = NULL;
4376 struct extent_state *cached_state = NULL;
4377 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4378 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4379 u64 block_end = ALIGN(size, root->sectorsize);
4380 u64 last_byte;
4381 u64 cur_offset;
4382 u64 hole_size;
4383 int err = 0;
4384
4385 if (size <= hole_start)
4386 return 0;
4387
4388 while (1) {
4389 struct btrfs_ordered_extent *ordered;
4390 btrfs_wait_ordered_range(inode, hole_start,
4391 block_end - hole_start);
4392 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4393 &cached_state);
4394 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
4395 if (!ordered)
4396 break;
4397 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4398 &cached_state, GFP_NOFS);
4399 btrfs_put_ordered_extent(ordered);
4400 }
4401
4402 cur_offset = hole_start;
4403 while (1) {
4404 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4405 block_end - cur_offset, 0);
4406 if (IS_ERR(em)) {
4407 err = PTR_ERR(em);
4408 em = NULL;
4409 break;
4410 }
4411 last_byte = min(extent_map_end(em), block_end);
4412 last_byte = ALIGN(last_byte , root->sectorsize);
4413 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4414 struct extent_map *hole_em;
4415 hole_size = last_byte - cur_offset;
4416
4417 trans = btrfs_start_transaction(root, 3);
4418 if (IS_ERR(trans)) {
4419 err = PTR_ERR(trans);
4420 break;
4421 }
4422
4423 err = btrfs_drop_extents(trans, root, inode,
4424 cur_offset,
4425 cur_offset + hole_size, 1);
4426 if (err) {
4427 btrfs_abort_transaction(trans, root, err);
4428 btrfs_end_transaction(trans, root);
4429 break;
4430 }
4431
4432 err = btrfs_insert_file_extent(trans, root,
4433 btrfs_ino(inode), cur_offset, 0,
4434 0, hole_size, 0, hole_size,
4435 0, 0, 0);
4436 if (err) {
4437 btrfs_abort_transaction(trans, root, err);
4438 btrfs_end_transaction(trans, root);
4439 break;
4440 }
4441
4442 btrfs_drop_extent_cache(inode, cur_offset,
4443 cur_offset + hole_size - 1, 0);
4444 hole_em = alloc_extent_map();
4445 if (!hole_em) {
4446 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4447 &BTRFS_I(inode)->runtime_flags);
4448 goto next;
4449 }
4450 hole_em->start = cur_offset;
4451 hole_em->len = hole_size;
4452 hole_em->orig_start = cur_offset;
4453
4454 hole_em->block_start = EXTENT_MAP_HOLE;
4455 hole_em->block_len = 0;
4456 hole_em->orig_block_len = 0;
4457 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4458 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4459 hole_em->generation = trans->transid;
4460
4461 while (1) {
4462 write_lock(&em_tree->lock);
4463 err = add_extent_mapping(em_tree, hole_em);
4464 if (!err)
4465 list_move(&hole_em->list,
4466 &em_tree->modified_extents);
4467 write_unlock(&em_tree->lock);
4468 if (err != -EEXIST)
4469 break;
4470 btrfs_drop_extent_cache(inode, cur_offset,
4471 cur_offset +
4472 hole_size - 1, 0);
4473 }
4474 free_extent_map(hole_em);
4475 next:
4476 btrfs_update_inode(trans, root, inode);
4477 btrfs_end_transaction(trans, root);
4478 }
4479 free_extent_map(em);
4480 em = NULL;
4481 cur_offset = last_byte;
4482 if (cur_offset >= block_end)
4483 break;
4484 }
4485
4486 free_extent_map(em);
4487 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4488 GFP_NOFS);
4489 return err;
4490 }
4491
4492 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4493 {
4494 struct btrfs_root *root = BTRFS_I(inode)->root;
4495 struct btrfs_trans_handle *trans;
4496 loff_t oldsize = i_size_read(inode);
4497 loff_t newsize = attr->ia_size;
4498 int mask = attr->ia_valid;
4499 int ret;
4500
4501 if (newsize == oldsize)
4502 return 0;
4503
4504 /*
4505 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4506 * special case where we need to update the times despite not having
4507 * these flags set. For all other operations the VFS set these flags
4508 * explicitly if it wants a timestamp update.
4509 */
4510 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
4511 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
4512
4513 if (newsize > oldsize) {
4514 truncate_pagecache(inode, oldsize, newsize);
4515 ret = btrfs_cont_expand(inode, oldsize, newsize);
4516 if (ret)
4517 return ret;
4518
4519 trans = btrfs_start_transaction(root, 1);
4520 if (IS_ERR(trans))
4521 return PTR_ERR(trans);
4522
4523 i_size_write(inode, newsize);
4524 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4525 ret = btrfs_update_inode(trans, root, inode);
4526 btrfs_end_transaction(trans, root);
4527 } else {
4528
4529 /*
4530 * We're truncating a file that used to have good data down to
4531 * zero. Make sure it gets into the ordered flush list so that
4532 * any new writes get down to disk quickly.
4533 */
4534 if (newsize == 0)
4535 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4536 &BTRFS_I(inode)->runtime_flags);
4537
4538 /*
4539 * 1 for the orphan item we're going to add
4540 * 1 for the orphan item deletion.
4541 */
4542 trans = btrfs_start_transaction(root, 2);
4543 if (IS_ERR(trans))
4544 return PTR_ERR(trans);
4545
4546 /*
4547 * We need to do this in case we fail at _any_ point during the
4548 * actual truncate. Once we do the truncate_setsize we could
4549 * invalidate pages which forces any outstanding ordered io to
4550 * be instantly completed which will give us extents that need
4551 * to be truncated. If we fail to get an orphan inode down we
4552 * could have left over extents that were never meant to live,
4553 * so we need to garuntee from this point on that everything
4554 * will be consistent.
4555 */
4556 ret = btrfs_orphan_add(trans, inode);
4557 btrfs_end_transaction(trans, root);
4558 if (ret)
4559 return ret;
4560
4561 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4562 truncate_setsize(inode, newsize);
4563
4564 /* Disable nonlocked read DIO to avoid the end less truncate */
4565 btrfs_inode_block_unlocked_dio(inode);
4566 inode_dio_wait(inode);
4567 btrfs_inode_resume_unlocked_dio(inode);
4568
4569 ret = btrfs_truncate(inode);
4570 if (ret && inode->i_nlink)
4571 btrfs_orphan_del(NULL, inode);
4572 }
4573
4574 return ret;
4575 }
4576
4577 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4578 {
4579 struct inode *inode = dentry->d_inode;
4580 struct btrfs_root *root = BTRFS_I(inode)->root;
4581 int err;
4582
4583 if (btrfs_root_readonly(root))
4584 return -EROFS;
4585
4586 err = inode_change_ok(inode, attr);
4587 if (err)
4588 return err;
4589
4590 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4591 err = btrfs_setsize(inode, attr);
4592 if (err)
4593 return err;
4594 }
4595
4596 if (attr->ia_valid) {
4597 setattr_copy(inode, attr);
4598 inode_inc_iversion(inode);
4599 err = btrfs_dirty_inode(inode);
4600
4601 if (!err && attr->ia_valid & ATTR_MODE)
4602 err = btrfs_acl_chmod(inode);
4603 }
4604
4605 return err;
4606 }
4607
4608 void btrfs_evict_inode(struct inode *inode)
4609 {
4610 struct btrfs_trans_handle *trans;
4611 struct btrfs_root *root = BTRFS_I(inode)->root;
4612 struct btrfs_block_rsv *rsv, *global_rsv;
4613 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4614 int ret;
4615
4616 trace_btrfs_inode_evict(inode);
4617
4618 truncate_inode_pages(&inode->i_data, 0);
4619 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
4620 btrfs_is_free_space_inode(inode)))
4621 goto no_delete;
4622
4623 if (is_bad_inode(inode)) {
4624 btrfs_orphan_del(NULL, inode);
4625 goto no_delete;
4626 }
4627 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4628 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4629
4630 if (root->fs_info->log_root_recovering) {
4631 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4632 &BTRFS_I(inode)->runtime_flags));
4633 goto no_delete;
4634 }
4635
4636 if (inode->i_nlink > 0) {
4637 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
4638 goto no_delete;
4639 }
4640
4641 ret = btrfs_commit_inode_delayed_inode(inode);
4642 if (ret) {
4643 btrfs_orphan_del(NULL, inode);
4644 goto no_delete;
4645 }
4646
4647 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4648 if (!rsv) {
4649 btrfs_orphan_del(NULL, inode);
4650 goto no_delete;
4651 }
4652 rsv->size = min_size;
4653 rsv->failfast = 1;
4654 global_rsv = &root->fs_info->global_block_rsv;
4655
4656 btrfs_i_size_write(inode, 0);
4657
4658 /*
4659 * This is a bit simpler than btrfs_truncate since we've already
4660 * reserved our space for our orphan item in the unlink, so we just
4661 * need to reserve some slack space in case we add bytes and update
4662 * inode item when doing the truncate.
4663 */
4664 while (1) {
4665 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4666 BTRFS_RESERVE_FLUSH_LIMIT);
4667
4668 /*
4669 * Try and steal from the global reserve since we will
4670 * likely not use this space anyway, we want to try as
4671 * hard as possible to get this to work.
4672 */
4673 if (ret)
4674 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4675
4676 if (ret) {
4677 btrfs_warn(root->fs_info,
4678 "Could not get space for a delete, will truncate on mount %d",
4679 ret);
4680 btrfs_orphan_del(NULL, inode);
4681 btrfs_free_block_rsv(root, rsv);
4682 goto no_delete;
4683 }
4684
4685 trans = btrfs_join_transaction(root);
4686 if (IS_ERR(trans)) {
4687 btrfs_orphan_del(NULL, inode);
4688 btrfs_free_block_rsv(root, rsv);
4689 goto no_delete;
4690 }
4691
4692 trans->block_rsv = rsv;
4693
4694 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4695 if (ret != -ENOSPC)
4696 break;
4697
4698 trans->block_rsv = &root->fs_info->trans_block_rsv;
4699 btrfs_end_transaction(trans, root);
4700 trans = NULL;
4701 btrfs_btree_balance_dirty(root);
4702 }
4703
4704 btrfs_free_block_rsv(root, rsv);
4705
4706 if (ret == 0) {
4707 trans->block_rsv = root->orphan_block_rsv;
4708 ret = btrfs_orphan_del(trans, inode);
4709 BUG_ON(ret);
4710 }
4711
4712 trans->block_rsv = &root->fs_info->trans_block_rsv;
4713 if (!(root == root->fs_info->tree_root ||
4714 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4715 btrfs_return_ino(root, btrfs_ino(inode));
4716
4717 btrfs_end_transaction(trans, root);
4718 btrfs_btree_balance_dirty(root);
4719 no_delete:
4720 clear_inode(inode);
4721 return;
4722 }
4723
4724 /*
4725 * this returns the key found in the dir entry in the location pointer.
4726 * If no dir entries were found, location->objectid is 0.
4727 */
4728 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4729 struct btrfs_key *location)
4730 {
4731 const char *name = dentry->d_name.name;
4732 int namelen = dentry->d_name.len;
4733 struct btrfs_dir_item *di;
4734 struct btrfs_path *path;
4735 struct btrfs_root *root = BTRFS_I(dir)->root;
4736 int ret = 0;
4737
4738 path = btrfs_alloc_path();
4739 if (!path)
4740 return -ENOMEM;
4741
4742 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4743 namelen, 0);
4744 if (IS_ERR(di))
4745 ret = PTR_ERR(di);
4746
4747 if (IS_ERR_OR_NULL(di))
4748 goto out_err;
4749
4750 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4751 out:
4752 btrfs_free_path(path);
4753 return ret;
4754 out_err:
4755 location->objectid = 0;
4756 goto out;
4757 }
4758
4759 /*
4760 * when we hit a tree root in a directory, the btrfs part of the inode
4761 * needs to be changed to reflect the root directory of the tree root. This
4762 * is kind of like crossing a mount point.
4763 */
4764 static int fixup_tree_root_location(struct btrfs_root *root,
4765 struct inode *dir,
4766 struct dentry *dentry,
4767 struct btrfs_key *location,
4768 struct btrfs_root **sub_root)
4769 {
4770 struct btrfs_path *path;
4771 struct btrfs_root *new_root;
4772 struct btrfs_root_ref *ref;
4773 struct extent_buffer *leaf;
4774 int ret;
4775 int err = 0;
4776
4777 path = btrfs_alloc_path();
4778 if (!path) {
4779 err = -ENOMEM;
4780 goto out;
4781 }
4782
4783 err = -ENOENT;
4784 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4785 BTRFS_I(dir)->root->root_key.objectid,
4786 location->objectid);
4787 if (ret) {
4788 if (ret < 0)
4789 err = ret;
4790 goto out;
4791 }
4792
4793 leaf = path->nodes[0];
4794 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4795 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4796 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4797 goto out;
4798
4799 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4800 (unsigned long)(ref + 1),
4801 dentry->d_name.len);
4802 if (ret)
4803 goto out;
4804
4805 btrfs_release_path(path);
4806
4807 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4808 if (IS_ERR(new_root)) {
4809 err = PTR_ERR(new_root);
4810 goto out;
4811 }
4812
4813 if (btrfs_root_refs(&new_root->root_item) == 0) {
4814 err = -ENOENT;
4815 goto out;
4816 }
4817
4818 *sub_root = new_root;
4819 location->objectid = btrfs_root_dirid(&new_root->root_item);
4820 location->type = BTRFS_INODE_ITEM_KEY;
4821 location->offset = 0;
4822 err = 0;
4823 out:
4824 btrfs_free_path(path);
4825 return err;
4826 }
4827
4828 static void inode_tree_add(struct inode *inode)
4829 {
4830 struct btrfs_root *root = BTRFS_I(inode)->root;
4831 struct btrfs_inode *entry;
4832 struct rb_node **p;
4833 struct rb_node *parent;
4834 u64 ino = btrfs_ino(inode);
4835 again:
4836 p = &root->inode_tree.rb_node;
4837 parent = NULL;
4838
4839 if (inode_unhashed(inode))
4840 return;
4841
4842 spin_lock(&root->inode_lock);
4843 while (*p) {
4844 parent = *p;
4845 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4846
4847 if (ino < btrfs_ino(&entry->vfs_inode))
4848 p = &parent->rb_left;
4849 else if (ino > btrfs_ino(&entry->vfs_inode))
4850 p = &parent->rb_right;
4851 else {
4852 WARN_ON(!(entry->vfs_inode.i_state &
4853 (I_WILL_FREE | I_FREEING)));
4854 rb_erase(parent, &root->inode_tree);
4855 RB_CLEAR_NODE(parent);
4856 spin_unlock(&root->inode_lock);
4857 goto again;
4858 }
4859 }
4860 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4861 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4862 spin_unlock(&root->inode_lock);
4863 }
4864
4865 static void inode_tree_del(struct inode *inode)
4866 {
4867 struct btrfs_root *root = BTRFS_I(inode)->root;
4868 int empty = 0;
4869
4870 spin_lock(&root->inode_lock);
4871 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4872 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4873 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4874 empty = RB_EMPTY_ROOT(&root->inode_tree);
4875 }
4876 spin_unlock(&root->inode_lock);
4877
4878 /*
4879 * Free space cache has inodes in the tree root, but the tree root has a
4880 * root_refs of 0, so this could end up dropping the tree root as a
4881 * snapshot, so we need the extra !root->fs_info->tree_root check to
4882 * make sure we don't drop it.
4883 */
4884 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4885 root != root->fs_info->tree_root) {
4886 synchronize_srcu(&root->fs_info->subvol_srcu);
4887 spin_lock(&root->inode_lock);
4888 empty = RB_EMPTY_ROOT(&root->inode_tree);
4889 spin_unlock(&root->inode_lock);
4890 if (empty)
4891 btrfs_add_dead_root(root);
4892 }
4893 }
4894
4895 void btrfs_invalidate_inodes(struct btrfs_root *root)
4896 {
4897 struct rb_node *node;
4898 struct rb_node *prev;
4899 struct btrfs_inode *entry;
4900 struct inode *inode;
4901 u64 objectid = 0;
4902
4903 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4904
4905 spin_lock(&root->inode_lock);
4906 again:
4907 node = root->inode_tree.rb_node;
4908 prev = NULL;
4909 while (node) {
4910 prev = node;
4911 entry = rb_entry(node, struct btrfs_inode, rb_node);
4912
4913 if (objectid < btrfs_ino(&entry->vfs_inode))
4914 node = node->rb_left;
4915 else if (objectid > btrfs_ino(&entry->vfs_inode))
4916 node = node->rb_right;
4917 else
4918 break;
4919 }
4920 if (!node) {
4921 while (prev) {
4922 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4923 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4924 node = prev;
4925 break;
4926 }
4927 prev = rb_next(prev);
4928 }
4929 }
4930 while (node) {
4931 entry = rb_entry(node, struct btrfs_inode, rb_node);
4932 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4933 inode = igrab(&entry->vfs_inode);
4934 if (inode) {
4935 spin_unlock(&root->inode_lock);
4936 if (atomic_read(&inode->i_count) > 1)
4937 d_prune_aliases(inode);
4938 /*
4939 * btrfs_drop_inode will have it removed from
4940 * the inode cache when its usage count
4941 * hits zero.
4942 */
4943 iput(inode);
4944 cond_resched();
4945 spin_lock(&root->inode_lock);
4946 goto again;
4947 }
4948
4949 if (cond_resched_lock(&root->inode_lock))
4950 goto again;
4951
4952 node = rb_next(node);
4953 }
4954 spin_unlock(&root->inode_lock);
4955 }
4956
4957 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4958 {
4959 struct btrfs_iget_args *args = p;
4960 inode->i_ino = args->ino;
4961 BTRFS_I(inode)->root = args->root;
4962 return 0;
4963 }
4964
4965 static int btrfs_find_actor(struct inode *inode, void *opaque)
4966 {
4967 struct btrfs_iget_args *args = opaque;
4968 return args->ino == btrfs_ino(inode) &&
4969 args->root == BTRFS_I(inode)->root;
4970 }
4971
4972 static struct inode *btrfs_iget_locked(struct super_block *s,
4973 u64 objectid,
4974 struct btrfs_root *root)
4975 {
4976 struct inode *inode;
4977 struct btrfs_iget_args args;
4978 args.ino = objectid;
4979 args.root = root;
4980
4981 inode = iget5_locked(s, objectid, btrfs_find_actor,
4982 btrfs_init_locked_inode,
4983 (void *)&args);
4984 return inode;
4985 }
4986
4987 /* Get an inode object given its location and corresponding root.
4988 * Returns in *is_new if the inode was read from disk
4989 */
4990 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4991 struct btrfs_root *root, int *new)
4992 {
4993 struct inode *inode;
4994
4995 inode = btrfs_iget_locked(s, location->objectid, root);
4996 if (!inode)
4997 return ERR_PTR(-ENOMEM);
4998
4999 if (inode->i_state & I_NEW) {
5000 BTRFS_I(inode)->root = root;
5001 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
5002 btrfs_read_locked_inode(inode);
5003 if (!is_bad_inode(inode)) {
5004 inode_tree_add(inode);
5005 unlock_new_inode(inode);
5006 if (new)
5007 *new = 1;
5008 } else {
5009 unlock_new_inode(inode);
5010 iput(inode);
5011 inode = ERR_PTR(-ESTALE);
5012 }
5013 }
5014
5015 return inode;
5016 }
5017
5018 static struct inode *new_simple_dir(struct super_block *s,
5019 struct btrfs_key *key,
5020 struct btrfs_root *root)
5021 {
5022 struct inode *inode = new_inode(s);
5023
5024 if (!inode)
5025 return ERR_PTR(-ENOMEM);
5026
5027 BTRFS_I(inode)->root = root;
5028 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5029 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5030
5031 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5032 inode->i_op = &btrfs_dir_ro_inode_operations;
5033 inode->i_fop = &simple_dir_operations;
5034 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5035 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5036
5037 return inode;
5038 }
5039
5040 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5041 {
5042 struct inode *inode;
5043 struct btrfs_root *root = BTRFS_I(dir)->root;
5044 struct btrfs_root *sub_root = root;
5045 struct btrfs_key location;
5046 int index;
5047 int ret = 0;
5048
5049 if (dentry->d_name.len > BTRFS_NAME_LEN)
5050 return ERR_PTR(-ENAMETOOLONG);
5051
5052 ret = btrfs_inode_by_name(dir, dentry, &location);
5053 if (ret < 0)
5054 return ERR_PTR(ret);
5055
5056 if (location.objectid == 0)
5057 return NULL;
5058
5059 if (location.type == BTRFS_INODE_ITEM_KEY) {
5060 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5061 return inode;
5062 }
5063
5064 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5065
5066 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5067 ret = fixup_tree_root_location(root, dir, dentry,
5068 &location, &sub_root);
5069 if (ret < 0) {
5070 if (ret != -ENOENT)
5071 inode = ERR_PTR(ret);
5072 else
5073 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5074 } else {
5075 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5076 }
5077 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5078
5079 if (!IS_ERR(inode) && root != sub_root) {
5080 down_read(&root->fs_info->cleanup_work_sem);
5081 if (!(inode->i_sb->s_flags & MS_RDONLY))
5082 ret = btrfs_orphan_cleanup(sub_root);
5083 up_read(&root->fs_info->cleanup_work_sem);
5084 if (ret)
5085 inode = ERR_PTR(ret);
5086 }
5087
5088 return inode;
5089 }
5090
5091 static int btrfs_dentry_delete(const struct dentry *dentry)
5092 {
5093 struct btrfs_root *root;
5094 struct inode *inode = dentry->d_inode;
5095
5096 if (!inode && !IS_ROOT(dentry))
5097 inode = dentry->d_parent->d_inode;
5098
5099 if (inode) {
5100 root = BTRFS_I(inode)->root;
5101 if (btrfs_root_refs(&root->root_item) == 0)
5102 return 1;
5103
5104 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5105 return 1;
5106 }
5107 return 0;
5108 }
5109
5110 static void btrfs_dentry_release(struct dentry *dentry)
5111 {
5112 if (dentry->d_fsdata)
5113 kfree(dentry->d_fsdata);
5114 }
5115
5116 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5117 unsigned int flags)
5118 {
5119 struct dentry *ret;
5120
5121 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
5122 return ret;
5123 }
5124
5125 unsigned char btrfs_filetype_table[] = {
5126 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5127 };
5128
5129 static int btrfs_real_readdir(struct file *filp, void *dirent,
5130 filldir_t filldir)
5131 {
5132 struct inode *inode = file_inode(filp);
5133 struct btrfs_root *root = BTRFS_I(inode)->root;
5134 struct btrfs_item *item;
5135 struct btrfs_dir_item *di;
5136 struct btrfs_key key;
5137 struct btrfs_key found_key;
5138 struct btrfs_path *path;
5139 struct list_head ins_list;
5140 struct list_head del_list;
5141 int ret;
5142 struct extent_buffer *leaf;
5143 int slot;
5144 unsigned char d_type;
5145 int over = 0;
5146 u32 di_cur;
5147 u32 di_total;
5148 u32 di_len;
5149 int key_type = BTRFS_DIR_INDEX_KEY;
5150 char tmp_name[32];
5151 char *name_ptr;
5152 int name_len;
5153 int is_curr = 0; /* filp->f_pos points to the current index? */
5154
5155 /* FIXME, use a real flag for deciding about the key type */
5156 if (root->fs_info->tree_root == root)
5157 key_type = BTRFS_DIR_ITEM_KEY;
5158
5159 /* special case for "." */
5160 if (filp->f_pos == 0) {
5161 over = filldir(dirent, ".", 1,
5162 filp->f_pos, btrfs_ino(inode), DT_DIR);
5163 if (over)
5164 return 0;
5165 filp->f_pos = 1;
5166 }
5167 /* special case for .., just use the back ref */
5168 if (filp->f_pos == 1) {
5169 u64 pino = parent_ino(filp->f_path.dentry);
5170 over = filldir(dirent, "..", 2,
5171 filp->f_pos, pino, DT_DIR);
5172 if (over)
5173 return 0;
5174 filp->f_pos = 2;
5175 }
5176 path = btrfs_alloc_path();
5177 if (!path)
5178 return -ENOMEM;
5179
5180 path->reada = 1;
5181
5182 if (key_type == BTRFS_DIR_INDEX_KEY) {
5183 INIT_LIST_HEAD(&ins_list);
5184 INIT_LIST_HEAD(&del_list);
5185 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5186 }
5187
5188 btrfs_set_key_type(&key, key_type);
5189 key.offset = filp->f_pos;
5190 key.objectid = btrfs_ino(inode);
5191
5192 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5193 if (ret < 0)
5194 goto err;
5195
5196 while (1) {
5197 leaf = path->nodes[0];
5198 slot = path->slots[0];
5199 if (slot >= btrfs_header_nritems(leaf)) {
5200 ret = btrfs_next_leaf(root, path);
5201 if (ret < 0)
5202 goto err;
5203 else if (ret > 0)
5204 break;
5205 continue;
5206 }
5207
5208 item = btrfs_item_nr(leaf, slot);
5209 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5210
5211 if (found_key.objectid != key.objectid)
5212 break;
5213 if (btrfs_key_type(&found_key) != key_type)
5214 break;
5215 if (found_key.offset < filp->f_pos)
5216 goto next;
5217 if (key_type == BTRFS_DIR_INDEX_KEY &&
5218 btrfs_should_delete_dir_index(&del_list,
5219 found_key.offset))
5220 goto next;
5221
5222 filp->f_pos = found_key.offset;
5223 is_curr = 1;
5224
5225 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5226 di_cur = 0;
5227 di_total = btrfs_item_size(leaf, item);
5228
5229 while (di_cur < di_total) {
5230 struct btrfs_key location;
5231
5232 if (verify_dir_item(root, leaf, di))
5233 break;
5234
5235 name_len = btrfs_dir_name_len(leaf, di);
5236 if (name_len <= sizeof(tmp_name)) {
5237 name_ptr = tmp_name;
5238 } else {
5239 name_ptr = kmalloc(name_len, GFP_NOFS);
5240 if (!name_ptr) {
5241 ret = -ENOMEM;
5242 goto err;
5243 }
5244 }
5245 read_extent_buffer(leaf, name_ptr,
5246 (unsigned long)(di + 1), name_len);
5247
5248 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5249 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5250
5251
5252 /* is this a reference to our own snapshot? If so
5253 * skip it.
5254 *
5255 * In contrast to old kernels, we insert the snapshot's
5256 * dir item and dir index after it has been created, so
5257 * we won't find a reference to our own snapshot. We
5258 * still keep the following code for backward
5259 * compatibility.
5260 */
5261 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5262 location.objectid == root->root_key.objectid) {
5263 over = 0;
5264 goto skip;
5265 }
5266 over = filldir(dirent, name_ptr, name_len,
5267 found_key.offset, location.objectid,
5268 d_type);
5269
5270 skip:
5271 if (name_ptr != tmp_name)
5272 kfree(name_ptr);
5273
5274 if (over)
5275 goto nopos;
5276 di_len = btrfs_dir_name_len(leaf, di) +
5277 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5278 di_cur += di_len;
5279 di = (struct btrfs_dir_item *)((char *)di + di_len);
5280 }
5281 next:
5282 path->slots[0]++;
5283 }
5284
5285 if (key_type == BTRFS_DIR_INDEX_KEY) {
5286 if (is_curr)
5287 filp->f_pos++;
5288 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
5289 &ins_list);
5290 if (ret)
5291 goto nopos;
5292 }
5293
5294 /* Reached end of directory/root. Bump pos past the last item. */
5295 if (key_type == BTRFS_DIR_INDEX_KEY)
5296 /*
5297 * 32-bit glibc will use getdents64, but then strtol -
5298 * so the last number we can serve is this.
5299 */
5300 filp->f_pos = 0x7fffffff;
5301 else
5302 filp->f_pos++;
5303 nopos:
5304 ret = 0;
5305 err:
5306 if (key_type == BTRFS_DIR_INDEX_KEY)
5307 btrfs_put_delayed_items(&ins_list, &del_list);
5308 btrfs_free_path(path);
5309 return ret;
5310 }
5311
5312 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5313 {
5314 struct btrfs_root *root = BTRFS_I(inode)->root;
5315 struct btrfs_trans_handle *trans;
5316 int ret = 0;
5317 bool nolock = false;
5318
5319 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5320 return 0;
5321
5322 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5323 nolock = true;
5324
5325 if (wbc->sync_mode == WB_SYNC_ALL) {
5326 if (nolock)
5327 trans = btrfs_join_transaction_nolock(root);
5328 else
5329 trans = btrfs_join_transaction(root);
5330 if (IS_ERR(trans))
5331 return PTR_ERR(trans);
5332 ret = btrfs_commit_transaction(trans, root);
5333 }
5334 return ret;
5335 }
5336
5337 /*
5338 * This is somewhat expensive, updating the tree every time the
5339 * inode changes. But, it is most likely to find the inode in cache.
5340 * FIXME, needs more benchmarking...there are no reasons other than performance
5341 * to keep or drop this code.
5342 */
5343 int btrfs_dirty_inode(struct inode *inode)
5344 {
5345 struct btrfs_root *root = BTRFS_I(inode)->root;
5346 struct btrfs_trans_handle *trans;
5347 int ret;
5348
5349 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5350 return 0;
5351
5352 trans = btrfs_join_transaction(root);
5353 if (IS_ERR(trans))
5354 return PTR_ERR(trans);
5355
5356 ret = btrfs_update_inode(trans, root, inode);
5357 if (ret && ret == -ENOSPC) {
5358 /* whoops, lets try again with the full transaction */
5359 btrfs_end_transaction(trans, root);
5360 trans = btrfs_start_transaction(root, 1);
5361 if (IS_ERR(trans))
5362 return PTR_ERR(trans);
5363
5364 ret = btrfs_update_inode(trans, root, inode);
5365 }
5366 btrfs_end_transaction(trans, root);
5367 if (BTRFS_I(inode)->delayed_node)
5368 btrfs_balance_delayed_items(root);
5369
5370 return ret;
5371 }
5372
5373 /*
5374 * This is a copy of file_update_time. We need this so we can return error on
5375 * ENOSPC for updating the inode in the case of file write and mmap writes.
5376 */
5377 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5378 int flags)
5379 {
5380 struct btrfs_root *root = BTRFS_I(inode)->root;
5381
5382 if (btrfs_root_readonly(root))
5383 return -EROFS;
5384
5385 if (flags & S_VERSION)
5386 inode_inc_iversion(inode);
5387 if (flags & S_CTIME)
5388 inode->i_ctime = *now;
5389 if (flags & S_MTIME)
5390 inode->i_mtime = *now;
5391 if (flags & S_ATIME)
5392 inode->i_atime = *now;
5393 return btrfs_dirty_inode(inode);
5394 }
5395
5396 /*
5397 * find the highest existing sequence number in a directory
5398 * and then set the in-memory index_cnt variable to reflect
5399 * free sequence numbers
5400 */
5401 static int btrfs_set_inode_index_count(struct inode *inode)
5402 {
5403 struct btrfs_root *root = BTRFS_I(inode)->root;
5404 struct btrfs_key key, found_key;
5405 struct btrfs_path *path;
5406 struct extent_buffer *leaf;
5407 int ret;
5408
5409 key.objectid = btrfs_ino(inode);
5410 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5411 key.offset = (u64)-1;
5412
5413 path = btrfs_alloc_path();
5414 if (!path)
5415 return -ENOMEM;
5416
5417 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5418 if (ret < 0)
5419 goto out;
5420 /* FIXME: we should be able to handle this */
5421 if (ret == 0)
5422 goto out;
5423 ret = 0;
5424
5425 /*
5426 * MAGIC NUMBER EXPLANATION:
5427 * since we search a directory based on f_pos we have to start at 2
5428 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5429 * else has to start at 2
5430 */
5431 if (path->slots[0] == 0) {
5432 BTRFS_I(inode)->index_cnt = 2;
5433 goto out;
5434 }
5435
5436 path->slots[0]--;
5437
5438 leaf = path->nodes[0];
5439 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5440
5441 if (found_key.objectid != btrfs_ino(inode) ||
5442 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5443 BTRFS_I(inode)->index_cnt = 2;
5444 goto out;
5445 }
5446
5447 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5448 out:
5449 btrfs_free_path(path);
5450 return ret;
5451 }
5452
5453 /*
5454 * helper to find a free sequence number in a given directory. This current
5455 * code is very simple, later versions will do smarter things in the btree
5456 */
5457 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5458 {
5459 int ret = 0;
5460
5461 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5462 ret = btrfs_inode_delayed_dir_index_count(dir);
5463 if (ret) {
5464 ret = btrfs_set_inode_index_count(dir);
5465 if (ret)
5466 return ret;
5467 }
5468 }
5469
5470 *index = BTRFS_I(dir)->index_cnt;
5471 BTRFS_I(dir)->index_cnt++;
5472
5473 return ret;
5474 }
5475
5476 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5477 struct btrfs_root *root,
5478 struct inode *dir,
5479 const char *name, int name_len,
5480 u64 ref_objectid, u64 objectid,
5481 umode_t mode, u64 *index)
5482 {
5483 struct inode *inode;
5484 struct btrfs_inode_item *inode_item;
5485 struct btrfs_key *location;
5486 struct btrfs_path *path;
5487 struct btrfs_inode_ref *ref;
5488 struct btrfs_key key[2];
5489 u32 sizes[2];
5490 unsigned long ptr;
5491 int ret;
5492 int owner;
5493
5494 path = btrfs_alloc_path();
5495 if (!path)
5496 return ERR_PTR(-ENOMEM);
5497
5498 inode = new_inode(root->fs_info->sb);
5499 if (!inode) {
5500 btrfs_free_path(path);
5501 return ERR_PTR(-ENOMEM);
5502 }
5503
5504 /*
5505 * we have to initialize this early, so we can reclaim the inode
5506 * number if we fail afterwards in this function.
5507 */
5508 inode->i_ino = objectid;
5509
5510 if (dir) {
5511 trace_btrfs_inode_request(dir);
5512
5513 ret = btrfs_set_inode_index(dir, index);
5514 if (ret) {
5515 btrfs_free_path(path);
5516 iput(inode);
5517 return ERR_PTR(ret);
5518 }
5519 }
5520 /*
5521 * index_cnt is ignored for everything but a dir,
5522 * btrfs_get_inode_index_count has an explanation for the magic
5523 * number
5524 */
5525 BTRFS_I(inode)->index_cnt = 2;
5526 BTRFS_I(inode)->root = root;
5527 BTRFS_I(inode)->generation = trans->transid;
5528 inode->i_generation = BTRFS_I(inode)->generation;
5529
5530 /*
5531 * We could have gotten an inode number from somebody who was fsynced
5532 * and then removed in this same transaction, so let's just set full
5533 * sync since it will be a full sync anyway and this will blow away the
5534 * old info in the log.
5535 */
5536 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5537
5538 if (S_ISDIR(mode))
5539 owner = 0;
5540 else
5541 owner = 1;
5542
5543 key[0].objectid = objectid;
5544 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5545 key[0].offset = 0;
5546
5547 /*
5548 * Start new inodes with an inode_ref. This is slightly more
5549 * efficient for small numbers of hard links since they will
5550 * be packed into one item. Extended refs will kick in if we
5551 * add more hard links than can fit in the ref item.
5552 */
5553 key[1].objectid = objectid;
5554 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5555 key[1].offset = ref_objectid;
5556
5557 sizes[0] = sizeof(struct btrfs_inode_item);
5558 sizes[1] = name_len + sizeof(*ref);
5559
5560 path->leave_spinning = 1;
5561 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5562 if (ret != 0)
5563 goto fail;
5564
5565 inode_init_owner(inode, dir, mode);
5566 inode_set_bytes(inode, 0);
5567 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5568 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5569 struct btrfs_inode_item);
5570 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5571 sizeof(*inode_item));
5572 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5573
5574 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5575 struct btrfs_inode_ref);
5576 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5577 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5578 ptr = (unsigned long)(ref + 1);
5579 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5580
5581 btrfs_mark_buffer_dirty(path->nodes[0]);
5582 btrfs_free_path(path);
5583
5584 location = &BTRFS_I(inode)->location;
5585 location->objectid = objectid;
5586 location->offset = 0;
5587 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5588
5589 btrfs_inherit_iflags(inode, dir);
5590
5591 if (S_ISREG(mode)) {
5592 if (btrfs_test_opt(root, NODATASUM))
5593 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5594 if (btrfs_test_opt(root, NODATACOW))
5595 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5596 BTRFS_INODE_NODATASUM;
5597 }
5598
5599 insert_inode_hash(inode);
5600 inode_tree_add(inode);
5601
5602 trace_btrfs_inode_new(inode);
5603 btrfs_set_inode_last_trans(trans, inode);
5604
5605 btrfs_update_root_times(trans, root);
5606
5607 return inode;
5608 fail:
5609 if (dir)
5610 BTRFS_I(dir)->index_cnt--;
5611 btrfs_free_path(path);
5612 iput(inode);
5613 return ERR_PTR(ret);
5614 }
5615
5616 static inline u8 btrfs_inode_type(struct inode *inode)
5617 {
5618 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5619 }
5620
5621 /*
5622 * utility function to add 'inode' into 'parent_inode' with
5623 * a give name and a given sequence number.
5624 * if 'add_backref' is true, also insert a backref from the
5625 * inode to the parent directory.
5626 */
5627 int btrfs_add_link(struct btrfs_trans_handle *trans,
5628 struct inode *parent_inode, struct inode *inode,
5629 const char *name, int name_len, int add_backref, u64 index)
5630 {
5631 int ret = 0;
5632 struct btrfs_key key;
5633 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5634 u64 ino = btrfs_ino(inode);
5635 u64 parent_ino = btrfs_ino(parent_inode);
5636
5637 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5638 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5639 } else {
5640 key.objectid = ino;
5641 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5642 key.offset = 0;
5643 }
5644
5645 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5646 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5647 key.objectid, root->root_key.objectid,
5648 parent_ino, index, name, name_len);
5649 } else if (add_backref) {
5650 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5651 parent_ino, index);
5652 }
5653
5654 /* Nothing to clean up yet */
5655 if (ret)
5656 return ret;
5657
5658 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5659 parent_inode, &key,
5660 btrfs_inode_type(inode), index);
5661 if (ret == -EEXIST || ret == -EOVERFLOW)
5662 goto fail_dir_item;
5663 else if (ret) {
5664 btrfs_abort_transaction(trans, root, ret);
5665 return ret;
5666 }
5667
5668 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5669 name_len * 2);
5670 inode_inc_iversion(parent_inode);
5671 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5672 ret = btrfs_update_inode(trans, root, parent_inode);
5673 if (ret)
5674 btrfs_abort_transaction(trans, root, ret);
5675 return ret;
5676
5677 fail_dir_item:
5678 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5679 u64 local_index;
5680 int err;
5681 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5682 key.objectid, root->root_key.objectid,
5683 parent_ino, &local_index, name, name_len);
5684
5685 } else if (add_backref) {
5686 u64 local_index;
5687 int err;
5688
5689 err = btrfs_del_inode_ref(trans, root, name, name_len,
5690 ino, parent_ino, &local_index);
5691 }
5692 return ret;
5693 }
5694
5695 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5696 struct inode *dir, struct dentry *dentry,
5697 struct inode *inode, int backref, u64 index)
5698 {
5699 int err = btrfs_add_link(trans, dir, inode,
5700 dentry->d_name.name, dentry->d_name.len,
5701 backref, index);
5702 if (err > 0)
5703 err = -EEXIST;
5704 return err;
5705 }
5706
5707 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5708 umode_t mode, dev_t rdev)
5709 {
5710 struct btrfs_trans_handle *trans;
5711 struct btrfs_root *root = BTRFS_I(dir)->root;
5712 struct inode *inode = NULL;
5713 int err;
5714 int drop_inode = 0;
5715 u64 objectid;
5716 u64 index = 0;
5717
5718 if (!new_valid_dev(rdev))
5719 return -EINVAL;
5720
5721 /*
5722 * 2 for inode item and ref
5723 * 2 for dir items
5724 * 1 for xattr if selinux is on
5725 */
5726 trans = btrfs_start_transaction(root, 5);
5727 if (IS_ERR(trans))
5728 return PTR_ERR(trans);
5729
5730 err = btrfs_find_free_ino(root, &objectid);
5731 if (err)
5732 goto out_unlock;
5733
5734 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5735 dentry->d_name.len, btrfs_ino(dir), objectid,
5736 mode, &index);
5737 if (IS_ERR(inode)) {
5738 err = PTR_ERR(inode);
5739 goto out_unlock;
5740 }
5741
5742 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5743 if (err) {
5744 drop_inode = 1;
5745 goto out_unlock;
5746 }
5747
5748 /*
5749 * If the active LSM wants to access the inode during
5750 * d_instantiate it needs these. Smack checks to see
5751 * if the filesystem supports xattrs by looking at the
5752 * ops vector.
5753 */
5754
5755 inode->i_op = &btrfs_special_inode_operations;
5756 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5757 if (err)
5758 drop_inode = 1;
5759 else {
5760 init_special_inode(inode, inode->i_mode, rdev);
5761 btrfs_update_inode(trans, root, inode);
5762 d_instantiate(dentry, inode);
5763 }
5764 out_unlock:
5765 btrfs_end_transaction(trans, root);
5766 btrfs_btree_balance_dirty(root);
5767 if (drop_inode) {
5768 inode_dec_link_count(inode);
5769 iput(inode);
5770 }
5771 return err;
5772 }
5773
5774 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5775 umode_t mode, bool excl)
5776 {
5777 struct btrfs_trans_handle *trans;
5778 struct btrfs_root *root = BTRFS_I(dir)->root;
5779 struct inode *inode = NULL;
5780 int drop_inode_on_err = 0;
5781 int err;
5782 u64 objectid;
5783 u64 index = 0;
5784
5785 /*
5786 * 2 for inode item and ref
5787 * 2 for dir items
5788 * 1 for xattr if selinux is on
5789 */
5790 trans = btrfs_start_transaction(root, 5);
5791 if (IS_ERR(trans))
5792 return PTR_ERR(trans);
5793
5794 err = btrfs_find_free_ino(root, &objectid);
5795 if (err)
5796 goto out_unlock;
5797
5798 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5799 dentry->d_name.len, btrfs_ino(dir), objectid,
5800 mode, &index);
5801 if (IS_ERR(inode)) {
5802 err = PTR_ERR(inode);
5803 goto out_unlock;
5804 }
5805 drop_inode_on_err = 1;
5806
5807 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5808 if (err)
5809 goto out_unlock;
5810
5811 err = btrfs_update_inode(trans, root, inode);
5812 if (err)
5813 goto out_unlock;
5814
5815 /*
5816 * If the active LSM wants to access the inode during
5817 * d_instantiate it needs these. Smack checks to see
5818 * if the filesystem supports xattrs by looking at the
5819 * ops vector.
5820 */
5821 inode->i_fop = &btrfs_file_operations;
5822 inode->i_op = &btrfs_file_inode_operations;
5823
5824 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5825 if (err)
5826 goto out_unlock;
5827
5828 inode->i_mapping->a_ops = &btrfs_aops;
5829 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5830 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5831 d_instantiate(dentry, inode);
5832
5833 out_unlock:
5834 btrfs_end_transaction(trans, root);
5835 if (err && drop_inode_on_err) {
5836 inode_dec_link_count(inode);
5837 iput(inode);
5838 }
5839 btrfs_btree_balance_dirty(root);
5840 return err;
5841 }
5842
5843 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5844 struct dentry *dentry)
5845 {
5846 struct btrfs_trans_handle *trans;
5847 struct btrfs_root *root = BTRFS_I(dir)->root;
5848 struct inode *inode = old_dentry->d_inode;
5849 u64 index;
5850 int err;
5851 int drop_inode = 0;
5852
5853 /* do not allow sys_link's with other subvols of the same device */
5854 if (root->objectid != BTRFS_I(inode)->root->objectid)
5855 return -EXDEV;
5856
5857 if (inode->i_nlink >= BTRFS_LINK_MAX)
5858 return -EMLINK;
5859
5860 err = btrfs_set_inode_index(dir, &index);
5861 if (err)
5862 goto fail;
5863
5864 /*
5865 * 2 items for inode and inode ref
5866 * 2 items for dir items
5867 * 1 item for parent inode
5868 */
5869 trans = btrfs_start_transaction(root, 5);
5870 if (IS_ERR(trans)) {
5871 err = PTR_ERR(trans);
5872 goto fail;
5873 }
5874
5875 btrfs_inc_nlink(inode);
5876 inode_inc_iversion(inode);
5877 inode->i_ctime = CURRENT_TIME;
5878 ihold(inode);
5879 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5880
5881 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5882
5883 if (err) {
5884 drop_inode = 1;
5885 } else {
5886 struct dentry *parent = dentry->d_parent;
5887 err = btrfs_update_inode(trans, root, inode);
5888 if (err)
5889 goto fail;
5890 d_instantiate(dentry, inode);
5891 btrfs_log_new_name(trans, inode, NULL, parent);
5892 }
5893
5894 btrfs_end_transaction(trans, root);
5895 fail:
5896 if (drop_inode) {
5897 inode_dec_link_count(inode);
5898 iput(inode);
5899 }
5900 btrfs_btree_balance_dirty(root);
5901 return err;
5902 }
5903
5904 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5905 {
5906 struct inode *inode = NULL;
5907 struct btrfs_trans_handle *trans;
5908 struct btrfs_root *root = BTRFS_I(dir)->root;
5909 int err = 0;
5910 int drop_on_err = 0;
5911 u64 objectid = 0;
5912 u64 index = 0;
5913
5914 /*
5915 * 2 items for inode and ref
5916 * 2 items for dir items
5917 * 1 for xattr if selinux is on
5918 */
5919 trans = btrfs_start_transaction(root, 5);
5920 if (IS_ERR(trans))
5921 return PTR_ERR(trans);
5922
5923 err = btrfs_find_free_ino(root, &objectid);
5924 if (err)
5925 goto out_fail;
5926
5927 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5928 dentry->d_name.len, btrfs_ino(dir), objectid,
5929 S_IFDIR | mode, &index);
5930 if (IS_ERR(inode)) {
5931 err = PTR_ERR(inode);
5932 goto out_fail;
5933 }
5934
5935 drop_on_err = 1;
5936
5937 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5938 if (err)
5939 goto out_fail;
5940
5941 inode->i_op = &btrfs_dir_inode_operations;
5942 inode->i_fop = &btrfs_dir_file_operations;
5943
5944 btrfs_i_size_write(inode, 0);
5945 err = btrfs_update_inode(trans, root, inode);
5946 if (err)
5947 goto out_fail;
5948
5949 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5950 dentry->d_name.len, 0, index);
5951 if (err)
5952 goto out_fail;
5953
5954 d_instantiate(dentry, inode);
5955 drop_on_err = 0;
5956
5957 out_fail:
5958 btrfs_end_transaction(trans, root);
5959 if (drop_on_err)
5960 iput(inode);
5961 btrfs_btree_balance_dirty(root);
5962 return err;
5963 }
5964
5965 /* helper for btfs_get_extent. Given an existing extent in the tree,
5966 * and an extent that you want to insert, deal with overlap and insert
5967 * the new extent into the tree.
5968 */
5969 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5970 struct extent_map *existing,
5971 struct extent_map *em,
5972 u64 map_start, u64 map_len)
5973 {
5974 u64 start_diff;
5975
5976 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5977 start_diff = map_start - em->start;
5978 em->start = map_start;
5979 em->len = map_len;
5980 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5981 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5982 em->block_start += start_diff;
5983 em->block_len -= start_diff;
5984 }
5985 return add_extent_mapping(em_tree, em);
5986 }
5987
5988 static noinline int uncompress_inline(struct btrfs_path *path,
5989 struct inode *inode, struct page *page,
5990 size_t pg_offset, u64 extent_offset,
5991 struct btrfs_file_extent_item *item)
5992 {
5993 int ret;
5994 struct extent_buffer *leaf = path->nodes[0];
5995 char *tmp;
5996 size_t max_size;
5997 unsigned long inline_size;
5998 unsigned long ptr;
5999 int compress_type;
6000
6001 WARN_ON(pg_offset != 0);
6002 compress_type = btrfs_file_extent_compression(leaf, item);
6003 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6004 inline_size = btrfs_file_extent_inline_item_len(leaf,
6005 btrfs_item_nr(leaf, path->slots[0]));
6006 tmp = kmalloc(inline_size, GFP_NOFS);
6007 if (!tmp)
6008 return -ENOMEM;
6009 ptr = btrfs_file_extent_inline_start(item);
6010
6011 read_extent_buffer(leaf, tmp, ptr, inline_size);
6012
6013 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6014 ret = btrfs_decompress(compress_type, tmp, page,
6015 extent_offset, inline_size, max_size);
6016 if (ret) {
6017 char *kaddr = kmap_atomic(page);
6018 unsigned long copy_size = min_t(u64,
6019 PAGE_CACHE_SIZE - pg_offset,
6020 max_size - extent_offset);
6021 memset(kaddr + pg_offset, 0, copy_size);
6022 kunmap_atomic(kaddr);
6023 }
6024 kfree(tmp);
6025 return 0;
6026 }
6027
6028 /*
6029 * a bit scary, this does extent mapping from logical file offset to the disk.
6030 * the ugly parts come from merging extents from the disk with the in-ram
6031 * representation. This gets more complex because of the data=ordered code,
6032 * where the in-ram extents might be locked pending data=ordered completion.
6033 *
6034 * This also copies inline extents directly into the page.
6035 */
6036
6037 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6038 size_t pg_offset, u64 start, u64 len,
6039 int create)
6040 {
6041 int ret;
6042 int err = 0;
6043 u64 bytenr;
6044 u64 extent_start = 0;
6045 u64 extent_end = 0;
6046 u64 objectid = btrfs_ino(inode);
6047 u32 found_type;
6048 struct btrfs_path *path = NULL;
6049 struct btrfs_root *root = BTRFS_I(inode)->root;
6050 struct btrfs_file_extent_item *item;
6051 struct extent_buffer *leaf;
6052 struct btrfs_key found_key;
6053 struct extent_map *em = NULL;
6054 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6055 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6056 struct btrfs_trans_handle *trans = NULL;
6057 int compress_type;
6058
6059 again:
6060 read_lock(&em_tree->lock);
6061 em = lookup_extent_mapping(em_tree, start, len);
6062 if (em)
6063 em->bdev = root->fs_info->fs_devices->latest_bdev;
6064 read_unlock(&em_tree->lock);
6065
6066 if (em) {
6067 if (em->start > start || em->start + em->len <= start)
6068 free_extent_map(em);
6069 else if (em->block_start == EXTENT_MAP_INLINE && page)
6070 free_extent_map(em);
6071 else
6072 goto out;
6073 }
6074 em = alloc_extent_map();
6075 if (!em) {
6076 err = -ENOMEM;
6077 goto out;
6078 }
6079 em->bdev = root->fs_info->fs_devices->latest_bdev;
6080 em->start = EXTENT_MAP_HOLE;
6081 em->orig_start = EXTENT_MAP_HOLE;
6082 em->len = (u64)-1;
6083 em->block_len = (u64)-1;
6084
6085 if (!path) {
6086 path = btrfs_alloc_path();
6087 if (!path) {
6088 err = -ENOMEM;
6089 goto out;
6090 }
6091 /*
6092 * Chances are we'll be called again, so go ahead and do
6093 * readahead
6094 */
6095 path->reada = 1;
6096 }
6097
6098 ret = btrfs_lookup_file_extent(trans, root, path,
6099 objectid, start, trans != NULL);
6100 if (ret < 0) {
6101 err = ret;
6102 goto out;
6103 }
6104
6105 if (ret != 0) {
6106 if (path->slots[0] == 0)
6107 goto not_found;
6108 path->slots[0]--;
6109 }
6110
6111 leaf = path->nodes[0];
6112 item = btrfs_item_ptr(leaf, path->slots[0],
6113 struct btrfs_file_extent_item);
6114 /* are we inside the extent that was found? */
6115 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6116 found_type = btrfs_key_type(&found_key);
6117 if (found_key.objectid != objectid ||
6118 found_type != BTRFS_EXTENT_DATA_KEY) {
6119 goto not_found;
6120 }
6121
6122 found_type = btrfs_file_extent_type(leaf, item);
6123 extent_start = found_key.offset;
6124 compress_type = btrfs_file_extent_compression(leaf, item);
6125 if (found_type == BTRFS_FILE_EXTENT_REG ||
6126 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6127 extent_end = extent_start +
6128 btrfs_file_extent_num_bytes(leaf, item);
6129 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6130 size_t size;
6131 size = btrfs_file_extent_inline_len(leaf, item);
6132 extent_end = ALIGN(extent_start + size, root->sectorsize);
6133 }
6134
6135 if (start >= extent_end) {
6136 path->slots[0]++;
6137 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6138 ret = btrfs_next_leaf(root, path);
6139 if (ret < 0) {
6140 err = ret;
6141 goto out;
6142 }
6143 if (ret > 0)
6144 goto not_found;
6145 leaf = path->nodes[0];
6146 }
6147 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6148 if (found_key.objectid != objectid ||
6149 found_key.type != BTRFS_EXTENT_DATA_KEY)
6150 goto not_found;
6151 if (start + len <= found_key.offset)
6152 goto not_found;
6153 em->start = start;
6154 em->orig_start = start;
6155 em->len = found_key.offset - start;
6156 goto not_found_em;
6157 }
6158
6159 if (found_type == BTRFS_FILE_EXTENT_REG ||
6160 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6161 em->start = extent_start;
6162 em->len = extent_end - extent_start;
6163 em->orig_start = extent_start -
6164 btrfs_file_extent_offset(leaf, item);
6165 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6166 item);
6167 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6168 if (bytenr == 0) {
6169 em->block_start = EXTENT_MAP_HOLE;
6170 goto insert;
6171 }
6172 if (compress_type != BTRFS_COMPRESS_NONE) {
6173 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6174 em->compress_type = compress_type;
6175 em->block_start = bytenr;
6176 em->block_len = em->orig_block_len;
6177 } else {
6178 bytenr += btrfs_file_extent_offset(leaf, item);
6179 em->block_start = bytenr;
6180 em->block_len = em->len;
6181 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6182 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6183 }
6184 goto insert;
6185 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6186 unsigned long ptr;
6187 char *map;
6188 size_t size;
6189 size_t extent_offset;
6190 size_t copy_size;
6191
6192 em->block_start = EXTENT_MAP_INLINE;
6193 if (!page || create) {
6194 em->start = extent_start;
6195 em->len = extent_end - extent_start;
6196 goto out;
6197 }
6198
6199 size = btrfs_file_extent_inline_len(leaf, item);
6200 extent_offset = page_offset(page) + pg_offset - extent_start;
6201 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6202 size - extent_offset);
6203 em->start = extent_start + extent_offset;
6204 em->len = ALIGN(copy_size, root->sectorsize);
6205 em->orig_block_len = em->len;
6206 em->orig_start = em->start;
6207 if (compress_type) {
6208 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6209 em->compress_type = compress_type;
6210 }
6211 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6212 if (create == 0 && !PageUptodate(page)) {
6213 if (btrfs_file_extent_compression(leaf, item) !=
6214 BTRFS_COMPRESS_NONE) {
6215 ret = uncompress_inline(path, inode, page,
6216 pg_offset,
6217 extent_offset, item);
6218 BUG_ON(ret); /* -ENOMEM */
6219 } else {
6220 map = kmap(page);
6221 read_extent_buffer(leaf, map + pg_offset, ptr,
6222 copy_size);
6223 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6224 memset(map + pg_offset + copy_size, 0,
6225 PAGE_CACHE_SIZE - pg_offset -
6226 copy_size);
6227 }
6228 kunmap(page);
6229 }
6230 flush_dcache_page(page);
6231 } else if (create && PageUptodate(page)) {
6232 BUG();
6233 if (!trans) {
6234 kunmap(page);
6235 free_extent_map(em);
6236 em = NULL;
6237
6238 btrfs_release_path(path);
6239 trans = btrfs_join_transaction(root);
6240
6241 if (IS_ERR(trans))
6242 return ERR_CAST(trans);
6243 goto again;
6244 }
6245 map = kmap(page);
6246 write_extent_buffer(leaf, map + pg_offset, ptr,
6247 copy_size);
6248 kunmap(page);
6249 btrfs_mark_buffer_dirty(leaf);
6250 }
6251 set_extent_uptodate(io_tree, em->start,
6252 extent_map_end(em) - 1, NULL, GFP_NOFS);
6253 goto insert;
6254 } else {
6255 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6256 }
6257 not_found:
6258 em->start = start;
6259 em->orig_start = start;
6260 em->len = len;
6261 not_found_em:
6262 em->block_start = EXTENT_MAP_HOLE;
6263 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6264 insert:
6265 btrfs_release_path(path);
6266 if (em->start > start || extent_map_end(em) <= start) {
6267 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6268 (unsigned long long)em->start,
6269 (unsigned long long)em->len,
6270 (unsigned long long)start,
6271 (unsigned long long)len);
6272 err = -EIO;
6273 goto out;
6274 }
6275
6276 err = 0;
6277 write_lock(&em_tree->lock);
6278 ret = add_extent_mapping(em_tree, em);
6279 /* it is possible that someone inserted the extent into the tree
6280 * while we had the lock dropped. It is also possible that
6281 * an overlapping map exists in the tree
6282 */
6283 if (ret == -EEXIST) {
6284 struct extent_map *existing;
6285
6286 ret = 0;
6287
6288 existing = lookup_extent_mapping(em_tree, start, len);
6289 if (existing && (existing->start > start ||
6290 existing->start + existing->len <= start)) {
6291 free_extent_map(existing);
6292 existing = NULL;
6293 }
6294 if (!existing) {
6295 existing = lookup_extent_mapping(em_tree, em->start,
6296 em->len);
6297 if (existing) {
6298 err = merge_extent_mapping(em_tree, existing,
6299 em, start,
6300 root->sectorsize);
6301 free_extent_map(existing);
6302 if (err) {
6303 free_extent_map(em);
6304 em = NULL;
6305 }
6306 } else {
6307 err = -EIO;
6308 free_extent_map(em);
6309 em = NULL;
6310 }
6311 } else {
6312 free_extent_map(em);
6313 em = existing;
6314 err = 0;
6315 }
6316 }
6317 write_unlock(&em_tree->lock);
6318 out:
6319
6320 if (em)
6321 trace_btrfs_get_extent(root, em);
6322
6323 if (path)
6324 btrfs_free_path(path);
6325 if (trans) {
6326 ret = btrfs_end_transaction(trans, root);
6327 if (!err)
6328 err = ret;
6329 }
6330 if (err) {
6331 free_extent_map(em);
6332 return ERR_PTR(err);
6333 }
6334 BUG_ON(!em); /* Error is always set */
6335 return em;
6336 }
6337
6338 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6339 size_t pg_offset, u64 start, u64 len,
6340 int create)
6341 {
6342 struct extent_map *em;
6343 struct extent_map *hole_em = NULL;
6344 u64 range_start = start;
6345 u64 end;
6346 u64 found;
6347 u64 found_end;
6348 int err = 0;
6349
6350 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6351 if (IS_ERR(em))
6352 return em;
6353 if (em) {
6354 /*
6355 * if our em maps to
6356 * - a hole or
6357 * - a pre-alloc extent,
6358 * there might actually be delalloc bytes behind it.
6359 */
6360 if (em->block_start != EXTENT_MAP_HOLE &&
6361 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6362 return em;
6363 else
6364 hole_em = em;
6365 }
6366
6367 /* check to see if we've wrapped (len == -1 or similar) */
6368 end = start + len;
6369 if (end < start)
6370 end = (u64)-1;
6371 else
6372 end -= 1;
6373
6374 em = NULL;
6375
6376 /* ok, we didn't find anything, lets look for delalloc */
6377 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6378 end, len, EXTENT_DELALLOC, 1);
6379 found_end = range_start + found;
6380 if (found_end < range_start)
6381 found_end = (u64)-1;
6382
6383 /*
6384 * we didn't find anything useful, return
6385 * the original results from get_extent()
6386 */
6387 if (range_start > end || found_end <= start) {
6388 em = hole_em;
6389 hole_em = NULL;
6390 goto out;
6391 }
6392
6393 /* adjust the range_start to make sure it doesn't
6394 * go backwards from the start they passed in
6395 */
6396 range_start = max(start,range_start);
6397 found = found_end - range_start;
6398
6399 if (found > 0) {
6400 u64 hole_start = start;
6401 u64 hole_len = len;
6402
6403 em = alloc_extent_map();
6404 if (!em) {
6405 err = -ENOMEM;
6406 goto out;
6407 }
6408 /*
6409 * when btrfs_get_extent can't find anything it
6410 * returns one huge hole
6411 *
6412 * make sure what it found really fits our range, and
6413 * adjust to make sure it is based on the start from
6414 * the caller
6415 */
6416 if (hole_em) {
6417 u64 calc_end = extent_map_end(hole_em);
6418
6419 if (calc_end <= start || (hole_em->start > end)) {
6420 free_extent_map(hole_em);
6421 hole_em = NULL;
6422 } else {
6423 hole_start = max(hole_em->start, start);
6424 hole_len = calc_end - hole_start;
6425 }
6426 }
6427 em->bdev = NULL;
6428 if (hole_em && range_start > hole_start) {
6429 /* our hole starts before our delalloc, so we
6430 * have to return just the parts of the hole
6431 * that go until the delalloc starts
6432 */
6433 em->len = min(hole_len,
6434 range_start - hole_start);
6435 em->start = hole_start;
6436 em->orig_start = hole_start;
6437 /*
6438 * don't adjust block start at all,
6439 * it is fixed at EXTENT_MAP_HOLE
6440 */
6441 em->block_start = hole_em->block_start;
6442 em->block_len = hole_len;
6443 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6444 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6445 } else {
6446 em->start = range_start;
6447 em->len = found;
6448 em->orig_start = range_start;
6449 em->block_start = EXTENT_MAP_DELALLOC;
6450 em->block_len = found;
6451 }
6452 } else if (hole_em) {
6453 return hole_em;
6454 }
6455 out:
6456
6457 free_extent_map(hole_em);
6458 if (err) {
6459 free_extent_map(em);
6460 return ERR_PTR(err);
6461 }
6462 return em;
6463 }
6464
6465 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6466 u64 start, u64 len)
6467 {
6468 struct btrfs_root *root = BTRFS_I(inode)->root;
6469 struct btrfs_trans_handle *trans;
6470 struct extent_map *em;
6471 struct btrfs_key ins;
6472 u64 alloc_hint;
6473 int ret;
6474
6475 trans = btrfs_join_transaction(root);
6476 if (IS_ERR(trans))
6477 return ERR_CAST(trans);
6478
6479 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
6480
6481 alloc_hint = get_extent_allocation_hint(inode, start, len);
6482 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
6483 alloc_hint, &ins, 1);
6484 if (ret) {
6485 em = ERR_PTR(ret);
6486 goto out;
6487 }
6488
6489 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6490 ins.offset, ins.offset, 0);
6491 if (IS_ERR(em))
6492 goto out;
6493
6494 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6495 ins.offset, ins.offset, 0);
6496 if (ret) {
6497 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6498 em = ERR_PTR(ret);
6499 }
6500 out:
6501 btrfs_end_transaction(trans, root);
6502 return em;
6503 }
6504
6505 /*
6506 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6507 * block must be cow'd
6508 */
6509 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
6510 struct inode *inode, u64 offset, u64 len)
6511 {
6512 struct btrfs_path *path;
6513 int ret;
6514 struct extent_buffer *leaf;
6515 struct btrfs_root *root = BTRFS_I(inode)->root;
6516 struct btrfs_file_extent_item *fi;
6517 struct btrfs_key key;
6518 u64 disk_bytenr;
6519 u64 backref_offset;
6520 u64 extent_end;
6521 u64 num_bytes;
6522 int slot;
6523 int found_type;
6524
6525 path = btrfs_alloc_path();
6526 if (!path)
6527 return -ENOMEM;
6528
6529 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
6530 offset, 0);
6531 if (ret < 0)
6532 goto out;
6533
6534 slot = path->slots[0];
6535 if (ret == 1) {
6536 if (slot == 0) {
6537 /* can't find the item, must cow */
6538 ret = 0;
6539 goto out;
6540 }
6541 slot--;
6542 }
6543 ret = 0;
6544 leaf = path->nodes[0];
6545 btrfs_item_key_to_cpu(leaf, &key, slot);
6546 if (key.objectid != btrfs_ino(inode) ||
6547 key.type != BTRFS_EXTENT_DATA_KEY) {
6548 /* not our file or wrong item type, must cow */
6549 goto out;
6550 }
6551
6552 if (key.offset > offset) {
6553 /* Wrong offset, must cow */
6554 goto out;
6555 }
6556
6557 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6558 found_type = btrfs_file_extent_type(leaf, fi);
6559 if (found_type != BTRFS_FILE_EXTENT_REG &&
6560 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6561 /* not a regular extent, must cow */
6562 goto out;
6563 }
6564 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6565 backref_offset = btrfs_file_extent_offset(leaf, fi);
6566
6567 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6568 if (extent_end < offset + len) {
6569 /* extent doesn't include our full range, must cow */
6570 goto out;
6571 }
6572
6573 if (btrfs_extent_readonly(root, disk_bytenr))
6574 goto out;
6575
6576 /*
6577 * look for other files referencing this extent, if we
6578 * find any we must cow
6579 */
6580 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6581 key.offset - backref_offset, disk_bytenr))
6582 goto out;
6583
6584 /*
6585 * adjust disk_bytenr and num_bytes to cover just the bytes
6586 * in this extent we are about to write. If there
6587 * are any csums in that range we have to cow in order
6588 * to keep the csums correct
6589 */
6590 disk_bytenr += backref_offset;
6591 disk_bytenr += offset - key.offset;
6592 num_bytes = min(offset + len, extent_end) - offset;
6593 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6594 goto out;
6595 /*
6596 * all of the above have passed, it is safe to overwrite this extent
6597 * without cow
6598 */
6599 ret = 1;
6600 out:
6601 btrfs_free_path(path);
6602 return ret;
6603 }
6604
6605 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6606 struct extent_state **cached_state, int writing)
6607 {
6608 struct btrfs_ordered_extent *ordered;
6609 int ret = 0;
6610
6611 while (1) {
6612 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6613 0, cached_state);
6614 /*
6615 * We're concerned with the entire range that we're going to be
6616 * doing DIO to, so we need to make sure theres no ordered
6617 * extents in this range.
6618 */
6619 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6620 lockend - lockstart + 1);
6621
6622 /*
6623 * We need to make sure there are no buffered pages in this
6624 * range either, we could have raced between the invalidate in
6625 * generic_file_direct_write and locking the extent. The
6626 * invalidate needs to happen so that reads after a write do not
6627 * get stale data.
6628 */
6629 if (!ordered && (!writing ||
6630 !test_range_bit(&BTRFS_I(inode)->io_tree,
6631 lockstart, lockend, EXTENT_UPTODATE, 0,
6632 *cached_state)))
6633 break;
6634
6635 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6636 cached_state, GFP_NOFS);
6637
6638 if (ordered) {
6639 btrfs_start_ordered_extent(inode, ordered, 1);
6640 btrfs_put_ordered_extent(ordered);
6641 } else {
6642 /* Screw you mmap */
6643 ret = filemap_write_and_wait_range(inode->i_mapping,
6644 lockstart,
6645 lockend);
6646 if (ret)
6647 break;
6648
6649 /*
6650 * If we found a page that couldn't be invalidated just
6651 * fall back to buffered.
6652 */
6653 ret = invalidate_inode_pages2_range(inode->i_mapping,
6654 lockstart >> PAGE_CACHE_SHIFT,
6655 lockend >> PAGE_CACHE_SHIFT);
6656 if (ret)
6657 break;
6658 }
6659
6660 cond_resched();
6661 }
6662
6663 return ret;
6664 }
6665
6666 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6667 u64 len, u64 orig_start,
6668 u64 block_start, u64 block_len,
6669 u64 orig_block_len, int type)
6670 {
6671 struct extent_map_tree *em_tree;
6672 struct extent_map *em;
6673 struct btrfs_root *root = BTRFS_I(inode)->root;
6674 int ret;
6675
6676 em_tree = &BTRFS_I(inode)->extent_tree;
6677 em = alloc_extent_map();
6678 if (!em)
6679 return ERR_PTR(-ENOMEM);
6680
6681 em->start = start;
6682 em->orig_start = orig_start;
6683 em->mod_start = start;
6684 em->mod_len = len;
6685 em->len = len;
6686 em->block_len = block_len;
6687 em->block_start = block_start;
6688 em->bdev = root->fs_info->fs_devices->latest_bdev;
6689 em->orig_block_len = orig_block_len;
6690 em->generation = -1;
6691 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6692 if (type == BTRFS_ORDERED_PREALLOC)
6693 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6694
6695 do {
6696 btrfs_drop_extent_cache(inode, em->start,
6697 em->start + em->len - 1, 0);
6698 write_lock(&em_tree->lock);
6699 ret = add_extent_mapping(em_tree, em);
6700 if (!ret)
6701 list_move(&em->list,
6702 &em_tree->modified_extents);
6703 write_unlock(&em_tree->lock);
6704 } while (ret == -EEXIST);
6705
6706 if (ret) {
6707 free_extent_map(em);
6708 return ERR_PTR(ret);
6709 }
6710
6711 return em;
6712 }
6713
6714
6715 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6716 struct buffer_head *bh_result, int create)
6717 {
6718 struct extent_map *em;
6719 struct btrfs_root *root = BTRFS_I(inode)->root;
6720 struct extent_state *cached_state = NULL;
6721 u64 start = iblock << inode->i_blkbits;
6722 u64 lockstart, lockend;
6723 u64 len = bh_result->b_size;
6724 struct btrfs_trans_handle *trans;
6725 int unlock_bits = EXTENT_LOCKED;
6726 int ret = 0;
6727
6728 if (create)
6729 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6730 else
6731 len = min_t(u64, len, root->sectorsize);
6732
6733 lockstart = start;
6734 lockend = start + len - 1;
6735
6736 /*
6737 * If this errors out it's because we couldn't invalidate pagecache for
6738 * this range and we need to fallback to buffered.
6739 */
6740 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6741 return -ENOTBLK;
6742
6743 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6744 if (IS_ERR(em)) {
6745 ret = PTR_ERR(em);
6746 goto unlock_err;
6747 }
6748
6749 /*
6750 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6751 * io. INLINE is special, and we could probably kludge it in here, but
6752 * it's still buffered so for safety lets just fall back to the generic
6753 * buffered path.
6754 *
6755 * For COMPRESSED we _have_ to read the entire extent in so we can
6756 * decompress it, so there will be buffering required no matter what we
6757 * do, so go ahead and fallback to buffered.
6758 *
6759 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6760 * to buffered IO. Don't blame me, this is the price we pay for using
6761 * the generic code.
6762 */
6763 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6764 em->block_start == EXTENT_MAP_INLINE) {
6765 free_extent_map(em);
6766 ret = -ENOTBLK;
6767 goto unlock_err;
6768 }
6769
6770 /* Just a good old fashioned hole, return */
6771 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6772 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6773 free_extent_map(em);
6774 goto unlock_err;
6775 }
6776
6777 /*
6778 * We don't allocate a new extent in the following cases
6779 *
6780 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6781 * existing extent.
6782 * 2) The extent is marked as PREALLOC. We're good to go here and can
6783 * just use the extent.
6784 *
6785 */
6786 if (!create) {
6787 len = min(len, em->len - (start - em->start));
6788 lockstart = start + len;
6789 goto unlock;
6790 }
6791
6792 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6793 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6794 em->block_start != EXTENT_MAP_HOLE)) {
6795 int type;
6796 int ret;
6797 u64 block_start;
6798
6799 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6800 type = BTRFS_ORDERED_PREALLOC;
6801 else
6802 type = BTRFS_ORDERED_NOCOW;
6803 len = min(len, em->len - (start - em->start));
6804 block_start = em->block_start + (start - em->start);
6805
6806 /*
6807 * we're not going to log anything, but we do need
6808 * to make sure the current transaction stays open
6809 * while we look for nocow cross refs
6810 */
6811 trans = btrfs_join_transaction(root);
6812 if (IS_ERR(trans))
6813 goto must_cow;
6814
6815 if (can_nocow_odirect(trans, inode, start, len) == 1) {
6816 u64 orig_start = em->orig_start;
6817 u64 orig_block_len = em->orig_block_len;
6818
6819 if (type == BTRFS_ORDERED_PREALLOC) {
6820 free_extent_map(em);
6821 em = create_pinned_em(inode, start, len,
6822 orig_start,
6823 block_start, len,
6824 orig_block_len, type);
6825 if (IS_ERR(em)) {
6826 btrfs_end_transaction(trans, root);
6827 goto unlock_err;
6828 }
6829 }
6830
6831 ret = btrfs_add_ordered_extent_dio(inode, start,
6832 block_start, len, len, type);
6833 btrfs_end_transaction(trans, root);
6834 if (ret) {
6835 free_extent_map(em);
6836 goto unlock_err;
6837 }
6838 goto unlock;
6839 }
6840 btrfs_end_transaction(trans, root);
6841 }
6842 must_cow:
6843 /*
6844 * this will cow the extent, reset the len in case we changed
6845 * it above
6846 */
6847 len = bh_result->b_size;
6848 free_extent_map(em);
6849 em = btrfs_new_extent_direct(inode, start, len);
6850 if (IS_ERR(em)) {
6851 ret = PTR_ERR(em);
6852 goto unlock_err;
6853 }
6854 len = min(len, em->len - (start - em->start));
6855 unlock:
6856 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6857 inode->i_blkbits;
6858 bh_result->b_size = len;
6859 bh_result->b_bdev = em->bdev;
6860 set_buffer_mapped(bh_result);
6861 if (create) {
6862 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6863 set_buffer_new(bh_result);
6864
6865 /*
6866 * Need to update the i_size under the extent lock so buffered
6867 * readers will get the updated i_size when we unlock.
6868 */
6869 if (start + len > i_size_read(inode))
6870 i_size_write(inode, start + len);
6871
6872 spin_lock(&BTRFS_I(inode)->lock);
6873 BTRFS_I(inode)->outstanding_extents++;
6874 spin_unlock(&BTRFS_I(inode)->lock);
6875
6876 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6877 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6878 &cached_state, GFP_NOFS);
6879 BUG_ON(ret);
6880 }
6881
6882 /*
6883 * In the case of write we need to clear and unlock the entire range,
6884 * in the case of read we need to unlock only the end area that we
6885 * aren't using if there is any left over space.
6886 */
6887 if (lockstart < lockend) {
6888 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6889 lockend, unlock_bits, 1, 0,
6890 &cached_state, GFP_NOFS);
6891 } else {
6892 free_extent_state(cached_state);
6893 }
6894
6895 free_extent_map(em);
6896
6897 return 0;
6898
6899 unlock_err:
6900 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6901 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6902 return ret;
6903 }
6904
6905 struct btrfs_dio_private {
6906 struct inode *inode;
6907 u64 logical_offset;
6908 u64 disk_bytenr;
6909 u64 bytes;
6910 void *private;
6911
6912 /* number of bios pending for this dio */
6913 atomic_t pending_bios;
6914
6915 /* IO errors */
6916 int errors;
6917
6918 struct bio *orig_bio;
6919 };
6920
6921 static void btrfs_endio_direct_read(struct bio *bio, int err)
6922 {
6923 struct btrfs_dio_private *dip = bio->bi_private;
6924 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6925 struct bio_vec *bvec = bio->bi_io_vec;
6926 struct inode *inode = dip->inode;
6927 struct btrfs_root *root = BTRFS_I(inode)->root;
6928 u64 start;
6929
6930 start = dip->logical_offset;
6931 do {
6932 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6933 struct page *page = bvec->bv_page;
6934 char *kaddr;
6935 u32 csum = ~(u32)0;
6936 u64 private = ~(u32)0;
6937 unsigned long flags;
6938
6939 if (get_state_private(&BTRFS_I(inode)->io_tree,
6940 start, &private))
6941 goto failed;
6942 local_irq_save(flags);
6943 kaddr = kmap_atomic(page);
6944 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6945 csum, bvec->bv_len);
6946 btrfs_csum_final(csum, (char *)&csum);
6947 kunmap_atomic(kaddr);
6948 local_irq_restore(flags);
6949
6950 flush_dcache_page(bvec->bv_page);
6951 if (csum != private) {
6952 failed:
6953 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u private %u",
6954 (unsigned long long)btrfs_ino(inode),
6955 (unsigned long long)start,
6956 csum, (unsigned)private);
6957 err = -EIO;
6958 }
6959 }
6960
6961 start += bvec->bv_len;
6962 bvec++;
6963 } while (bvec <= bvec_end);
6964
6965 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6966 dip->logical_offset + dip->bytes - 1);
6967 bio->bi_private = dip->private;
6968
6969 kfree(dip);
6970
6971 /* If we had a csum failure make sure to clear the uptodate flag */
6972 if (err)
6973 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6974 dio_end_io(bio, err);
6975 }
6976
6977 static void btrfs_endio_direct_write(struct bio *bio, int err)
6978 {
6979 struct btrfs_dio_private *dip = bio->bi_private;
6980 struct inode *inode = dip->inode;
6981 struct btrfs_root *root = BTRFS_I(inode)->root;
6982 struct btrfs_ordered_extent *ordered = NULL;
6983 u64 ordered_offset = dip->logical_offset;
6984 u64 ordered_bytes = dip->bytes;
6985 int ret;
6986
6987 if (err)
6988 goto out_done;
6989 again:
6990 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6991 &ordered_offset,
6992 ordered_bytes, !err);
6993 if (!ret)
6994 goto out_test;
6995
6996 ordered->work.func = finish_ordered_fn;
6997 ordered->work.flags = 0;
6998 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6999 &ordered->work);
7000 out_test:
7001 /*
7002 * our bio might span multiple ordered extents. If we haven't
7003 * completed the accounting for the whole dio, go back and try again
7004 */
7005 if (ordered_offset < dip->logical_offset + dip->bytes) {
7006 ordered_bytes = dip->logical_offset + dip->bytes -
7007 ordered_offset;
7008 ordered = NULL;
7009 goto again;
7010 }
7011 out_done:
7012 bio->bi_private = dip->private;
7013
7014 kfree(dip);
7015
7016 /* If we had an error make sure to clear the uptodate flag */
7017 if (err)
7018 clear_bit(BIO_UPTODATE, &bio->bi_flags);
7019 dio_end_io(bio, err);
7020 }
7021
7022 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7023 struct bio *bio, int mirror_num,
7024 unsigned long bio_flags, u64 offset)
7025 {
7026 int ret;
7027 struct btrfs_root *root = BTRFS_I(inode)->root;
7028 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7029 BUG_ON(ret); /* -ENOMEM */
7030 return 0;
7031 }
7032
7033 static void btrfs_end_dio_bio(struct bio *bio, int err)
7034 {
7035 struct btrfs_dio_private *dip = bio->bi_private;
7036
7037 if (err) {
7038 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
7039 "sector %#Lx len %u err no %d\n",
7040 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
7041 (unsigned long long)bio->bi_sector, bio->bi_size, err);
7042 dip->errors = 1;
7043
7044 /*
7045 * before atomic variable goto zero, we must make sure
7046 * dip->errors is perceived to be set.
7047 */
7048 smp_mb__before_atomic_dec();
7049 }
7050
7051 /* if there are more bios still pending for this dio, just exit */
7052 if (!atomic_dec_and_test(&dip->pending_bios))
7053 goto out;
7054
7055 if (dip->errors)
7056 bio_io_error(dip->orig_bio);
7057 else {
7058 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
7059 bio_endio(dip->orig_bio, 0);
7060 }
7061 out:
7062 bio_put(bio);
7063 }
7064
7065 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7066 u64 first_sector, gfp_t gfp_flags)
7067 {
7068 int nr_vecs = bio_get_nr_vecs(bdev);
7069 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7070 }
7071
7072 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7073 int rw, u64 file_offset, int skip_sum,
7074 int async_submit)
7075 {
7076 int write = rw & REQ_WRITE;
7077 struct btrfs_root *root = BTRFS_I(inode)->root;
7078 int ret;
7079
7080 if (async_submit)
7081 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7082
7083 bio_get(bio);
7084
7085 if (!write) {
7086 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7087 if (ret)
7088 goto err;
7089 }
7090
7091 if (skip_sum)
7092 goto map;
7093
7094 if (write && async_submit) {
7095 ret = btrfs_wq_submit_bio(root->fs_info,
7096 inode, rw, bio, 0, 0,
7097 file_offset,
7098 __btrfs_submit_bio_start_direct_io,
7099 __btrfs_submit_bio_done);
7100 goto err;
7101 } else if (write) {
7102 /*
7103 * If we aren't doing async submit, calculate the csum of the
7104 * bio now.
7105 */
7106 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7107 if (ret)
7108 goto err;
7109 } else if (!skip_sum) {
7110 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
7111 if (ret)
7112 goto err;
7113 }
7114
7115 map:
7116 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7117 err:
7118 bio_put(bio);
7119 return ret;
7120 }
7121
7122 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7123 int skip_sum)
7124 {
7125 struct inode *inode = dip->inode;
7126 struct btrfs_root *root = BTRFS_I(inode)->root;
7127 struct bio *bio;
7128 struct bio *orig_bio = dip->orig_bio;
7129 struct bio_vec *bvec = orig_bio->bi_io_vec;
7130 u64 start_sector = orig_bio->bi_sector;
7131 u64 file_offset = dip->logical_offset;
7132 u64 submit_len = 0;
7133 u64 map_length;
7134 int nr_pages = 0;
7135 int ret = 0;
7136 int async_submit = 0;
7137
7138 map_length = orig_bio->bi_size;
7139 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7140 &map_length, NULL, 0);
7141 if (ret) {
7142 bio_put(orig_bio);
7143 return -EIO;
7144 }
7145 if (map_length >= orig_bio->bi_size) {
7146 bio = orig_bio;
7147 goto submit;
7148 }
7149
7150 /* async crcs make it difficult to collect full stripe writes. */
7151 if (btrfs_get_alloc_profile(root, 1) &
7152 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7153 async_submit = 0;
7154 else
7155 async_submit = 1;
7156
7157 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7158 if (!bio)
7159 return -ENOMEM;
7160 bio->bi_private = dip;
7161 bio->bi_end_io = btrfs_end_dio_bio;
7162 atomic_inc(&dip->pending_bios);
7163
7164 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7165 if (unlikely(map_length < submit_len + bvec->bv_len ||
7166 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7167 bvec->bv_offset) < bvec->bv_len)) {
7168 /*
7169 * inc the count before we submit the bio so
7170 * we know the end IO handler won't happen before
7171 * we inc the count. Otherwise, the dip might get freed
7172 * before we're done setting it up
7173 */
7174 atomic_inc(&dip->pending_bios);
7175 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7176 file_offset, skip_sum,
7177 async_submit);
7178 if (ret) {
7179 bio_put(bio);
7180 atomic_dec(&dip->pending_bios);
7181 goto out_err;
7182 }
7183
7184 start_sector += submit_len >> 9;
7185 file_offset += submit_len;
7186
7187 submit_len = 0;
7188 nr_pages = 0;
7189
7190 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7191 start_sector, GFP_NOFS);
7192 if (!bio)
7193 goto out_err;
7194 bio->bi_private = dip;
7195 bio->bi_end_io = btrfs_end_dio_bio;
7196
7197 map_length = orig_bio->bi_size;
7198 ret = btrfs_map_block(root->fs_info, rw,
7199 start_sector << 9,
7200 &map_length, NULL, 0);
7201 if (ret) {
7202 bio_put(bio);
7203 goto out_err;
7204 }
7205 } else {
7206 submit_len += bvec->bv_len;
7207 nr_pages ++;
7208 bvec++;
7209 }
7210 }
7211
7212 submit:
7213 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7214 async_submit);
7215 if (!ret)
7216 return 0;
7217
7218 bio_put(bio);
7219 out_err:
7220 dip->errors = 1;
7221 /*
7222 * before atomic variable goto zero, we must
7223 * make sure dip->errors is perceived to be set.
7224 */
7225 smp_mb__before_atomic_dec();
7226 if (atomic_dec_and_test(&dip->pending_bios))
7227 bio_io_error(dip->orig_bio);
7228
7229 /* bio_end_io() will handle error, so we needn't return it */
7230 return 0;
7231 }
7232
7233 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
7234 loff_t file_offset)
7235 {
7236 struct btrfs_root *root = BTRFS_I(inode)->root;
7237 struct btrfs_dio_private *dip;
7238 struct bio_vec *bvec = bio->bi_io_vec;
7239 int skip_sum;
7240 int write = rw & REQ_WRITE;
7241 int ret = 0;
7242
7243 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7244
7245 dip = kmalloc(sizeof(*dip), GFP_NOFS);
7246 if (!dip) {
7247 ret = -ENOMEM;
7248 goto free_ordered;
7249 }
7250
7251 dip->private = bio->bi_private;
7252 dip->inode = inode;
7253 dip->logical_offset = file_offset;
7254
7255 dip->bytes = 0;
7256 do {
7257 dip->bytes += bvec->bv_len;
7258 bvec++;
7259 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
7260
7261 dip->disk_bytenr = (u64)bio->bi_sector << 9;
7262 bio->bi_private = dip;
7263 dip->errors = 0;
7264 dip->orig_bio = bio;
7265 atomic_set(&dip->pending_bios, 0);
7266
7267 if (write)
7268 bio->bi_end_io = btrfs_endio_direct_write;
7269 else
7270 bio->bi_end_io = btrfs_endio_direct_read;
7271
7272 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7273 if (!ret)
7274 return;
7275 free_ordered:
7276 /*
7277 * If this is a write, we need to clean up the reserved space and kill
7278 * the ordered extent.
7279 */
7280 if (write) {
7281 struct btrfs_ordered_extent *ordered;
7282 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7283 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7284 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7285 btrfs_free_reserved_extent(root, ordered->start,
7286 ordered->disk_len);
7287 btrfs_put_ordered_extent(ordered);
7288 btrfs_put_ordered_extent(ordered);
7289 }
7290 bio_endio(bio, ret);
7291 }
7292
7293 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7294 const struct iovec *iov, loff_t offset,
7295 unsigned long nr_segs)
7296 {
7297 int seg;
7298 int i;
7299 size_t size;
7300 unsigned long addr;
7301 unsigned blocksize_mask = root->sectorsize - 1;
7302 ssize_t retval = -EINVAL;
7303 loff_t end = offset;
7304
7305 if (offset & blocksize_mask)
7306 goto out;
7307
7308 /* Check the memory alignment. Blocks cannot straddle pages */
7309 for (seg = 0; seg < nr_segs; seg++) {
7310 addr = (unsigned long)iov[seg].iov_base;
7311 size = iov[seg].iov_len;
7312 end += size;
7313 if ((addr & blocksize_mask) || (size & blocksize_mask))
7314 goto out;
7315
7316 /* If this is a write we don't need to check anymore */
7317 if (rw & WRITE)
7318 continue;
7319
7320 /*
7321 * Check to make sure we don't have duplicate iov_base's in this
7322 * iovec, if so return EINVAL, otherwise we'll get csum errors
7323 * when reading back.
7324 */
7325 for (i = seg + 1; i < nr_segs; i++) {
7326 if (iov[seg].iov_base == iov[i].iov_base)
7327 goto out;
7328 }
7329 }
7330 retval = 0;
7331 out:
7332 return retval;
7333 }
7334
7335 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7336 const struct iovec *iov, loff_t offset,
7337 unsigned long nr_segs)
7338 {
7339 struct file *file = iocb->ki_filp;
7340 struct inode *inode = file->f_mapping->host;
7341 size_t count = 0;
7342 int flags = 0;
7343 bool wakeup = true;
7344 bool relock = false;
7345 ssize_t ret;
7346
7347 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7348 offset, nr_segs))
7349 return 0;
7350
7351 atomic_inc(&inode->i_dio_count);
7352 smp_mb__after_atomic_inc();
7353
7354 if (rw & WRITE) {
7355 count = iov_length(iov, nr_segs);
7356 /*
7357 * If the write DIO is beyond the EOF, we need update
7358 * the isize, but it is protected by i_mutex. So we can
7359 * not unlock the i_mutex at this case.
7360 */
7361 if (offset + count <= inode->i_size) {
7362 mutex_unlock(&inode->i_mutex);
7363 relock = true;
7364 }
7365 ret = btrfs_delalloc_reserve_space(inode, count);
7366 if (ret)
7367 goto out;
7368 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7369 &BTRFS_I(inode)->runtime_flags))) {
7370 inode_dio_done(inode);
7371 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7372 wakeup = false;
7373 }
7374
7375 ret = __blockdev_direct_IO(rw, iocb, inode,
7376 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7377 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7378 btrfs_submit_direct, flags);
7379 if (rw & WRITE) {
7380 if (ret < 0 && ret != -EIOCBQUEUED)
7381 btrfs_delalloc_release_space(inode, count);
7382 else if (ret >= 0 && (size_t)ret < count)
7383 btrfs_delalloc_release_space(inode,
7384 count - (size_t)ret);
7385 else
7386 btrfs_delalloc_release_metadata(inode, 0);
7387 }
7388 out:
7389 if (wakeup)
7390 inode_dio_done(inode);
7391 if (relock)
7392 mutex_lock(&inode->i_mutex);
7393
7394 return ret;
7395 }
7396
7397 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7398
7399 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7400 __u64 start, __u64 len)
7401 {
7402 int ret;
7403
7404 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7405 if (ret)
7406 return ret;
7407
7408 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7409 }
7410
7411 int btrfs_readpage(struct file *file, struct page *page)
7412 {
7413 struct extent_io_tree *tree;
7414 tree = &BTRFS_I(page->mapping->host)->io_tree;
7415 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7416 }
7417
7418 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7419 {
7420 struct extent_io_tree *tree;
7421
7422
7423 if (current->flags & PF_MEMALLOC) {
7424 redirty_page_for_writepage(wbc, page);
7425 unlock_page(page);
7426 return 0;
7427 }
7428 tree = &BTRFS_I(page->mapping->host)->io_tree;
7429 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7430 }
7431
7432 int btrfs_writepages(struct address_space *mapping,
7433 struct writeback_control *wbc)
7434 {
7435 struct extent_io_tree *tree;
7436
7437 tree = &BTRFS_I(mapping->host)->io_tree;
7438 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7439 }
7440
7441 static int
7442 btrfs_readpages(struct file *file, struct address_space *mapping,
7443 struct list_head *pages, unsigned nr_pages)
7444 {
7445 struct extent_io_tree *tree;
7446 tree = &BTRFS_I(mapping->host)->io_tree;
7447 return extent_readpages(tree, mapping, pages, nr_pages,
7448 btrfs_get_extent);
7449 }
7450 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7451 {
7452 struct extent_io_tree *tree;
7453 struct extent_map_tree *map;
7454 int ret;
7455
7456 tree = &BTRFS_I(page->mapping->host)->io_tree;
7457 map = &BTRFS_I(page->mapping->host)->extent_tree;
7458 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7459 if (ret == 1) {
7460 ClearPagePrivate(page);
7461 set_page_private(page, 0);
7462 page_cache_release(page);
7463 }
7464 return ret;
7465 }
7466
7467 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7468 {
7469 if (PageWriteback(page) || PageDirty(page))
7470 return 0;
7471 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7472 }
7473
7474 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
7475 {
7476 struct inode *inode = page->mapping->host;
7477 struct extent_io_tree *tree;
7478 struct btrfs_ordered_extent *ordered;
7479 struct extent_state *cached_state = NULL;
7480 u64 page_start = page_offset(page);
7481 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7482
7483 /*
7484 * we have the page locked, so new writeback can't start,
7485 * and the dirty bit won't be cleared while we are here.
7486 *
7487 * Wait for IO on this page so that we can safely clear
7488 * the PagePrivate2 bit and do ordered accounting
7489 */
7490 wait_on_page_writeback(page);
7491
7492 tree = &BTRFS_I(inode)->io_tree;
7493 if (offset) {
7494 btrfs_releasepage(page, GFP_NOFS);
7495 return;
7496 }
7497 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7498 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
7499 if (ordered) {
7500 /*
7501 * IO on this page will never be started, so we need
7502 * to account for any ordered extents now
7503 */
7504 clear_extent_bit(tree, page_start, page_end,
7505 EXTENT_DIRTY | EXTENT_DELALLOC |
7506 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7507 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
7508 /*
7509 * whoever cleared the private bit is responsible
7510 * for the finish_ordered_io
7511 */
7512 if (TestClearPagePrivate2(page) &&
7513 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
7514 PAGE_CACHE_SIZE, 1)) {
7515 btrfs_finish_ordered_io(ordered);
7516 }
7517 btrfs_put_ordered_extent(ordered);
7518 cached_state = NULL;
7519 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7520 }
7521 clear_extent_bit(tree, page_start, page_end,
7522 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
7523 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
7524 &cached_state, GFP_NOFS);
7525 __btrfs_releasepage(page, GFP_NOFS);
7526
7527 ClearPageChecked(page);
7528 if (PagePrivate(page)) {
7529 ClearPagePrivate(page);
7530 set_page_private(page, 0);
7531 page_cache_release(page);
7532 }
7533 }
7534
7535 /*
7536 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7537 * called from a page fault handler when a page is first dirtied. Hence we must
7538 * be careful to check for EOF conditions here. We set the page up correctly
7539 * for a written page which means we get ENOSPC checking when writing into
7540 * holes and correct delalloc and unwritten extent mapping on filesystems that
7541 * support these features.
7542 *
7543 * We are not allowed to take the i_mutex here so we have to play games to
7544 * protect against truncate races as the page could now be beyond EOF. Because
7545 * vmtruncate() writes the inode size before removing pages, once we have the
7546 * page lock we can determine safely if the page is beyond EOF. If it is not
7547 * beyond EOF, then the page is guaranteed safe against truncation until we
7548 * unlock the page.
7549 */
7550 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7551 {
7552 struct page *page = vmf->page;
7553 struct inode *inode = file_inode(vma->vm_file);
7554 struct btrfs_root *root = BTRFS_I(inode)->root;
7555 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7556 struct btrfs_ordered_extent *ordered;
7557 struct extent_state *cached_state = NULL;
7558 char *kaddr;
7559 unsigned long zero_start;
7560 loff_t size;
7561 int ret;
7562 int reserved = 0;
7563 u64 page_start;
7564 u64 page_end;
7565
7566 sb_start_pagefault(inode->i_sb);
7567 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7568 if (!ret) {
7569 ret = file_update_time(vma->vm_file);
7570 reserved = 1;
7571 }
7572 if (ret) {
7573 if (ret == -ENOMEM)
7574 ret = VM_FAULT_OOM;
7575 else /* -ENOSPC, -EIO, etc */
7576 ret = VM_FAULT_SIGBUS;
7577 if (reserved)
7578 goto out;
7579 goto out_noreserve;
7580 }
7581
7582 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7583 again:
7584 lock_page(page);
7585 size = i_size_read(inode);
7586 page_start = page_offset(page);
7587 page_end = page_start + PAGE_CACHE_SIZE - 1;
7588
7589 if ((page->mapping != inode->i_mapping) ||
7590 (page_start >= size)) {
7591 /* page got truncated out from underneath us */
7592 goto out_unlock;
7593 }
7594 wait_on_page_writeback(page);
7595
7596 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7597 set_page_extent_mapped(page);
7598
7599 /*
7600 * we can't set the delalloc bits if there are pending ordered
7601 * extents. Drop our locks and wait for them to finish
7602 */
7603 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7604 if (ordered) {
7605 unlock_extent_cached(io_tree, page_start, page_end,
7606 &cached_state, GFP_NOFS);
7607 unlock_page(page);
7608 btrfs_start_ordered_extent(inode, ordered, 1);
7609 btrfs_put_ordered_extent(ordered);
7610 goto again;
7611 }
7612
7613 /*
7614 * XXX - page_mkwrite gets called every time the page is dirtied, even
7615 * if it was already dirty, so for space accounting reasons we need to
7616 * clear any delalloc bits for the range we are fixing to save. There
7617 * is probably a better way to do this, but for now keep consistent with
7618 * prepare_pages in the normal write path.
7619 */
7620 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7621 EXTENT_DIRTY | EXTENT_DELALLOC |
7622 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7623 0, 0, &cached_state, GFP_NOFS);
7624
7625 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7626 &cached_state);
7627 if (ret) {
7628 unlock_extent_cached(io_tree, page_start, page_end,
7629 &cached_state, GFP_NOFS);
7630 ret = VM_FAULT_SIGBUS;
7631 goto out_unlock;
7632 }
7633 ret = 0;
7634
7635 /* page is wholly or partially inside EOF */
7636 if (page_start + PAGE_CACHE_SIZE > size)
7637 zero_start = size & ~PAGE_CACHE_MASK;
7638 else
7639 zero_start = PAGE_CACHE_SIZE;
7640
7641 if (zero_start != PAGE_CACHE_SIZE) {
7642 kaddr = kmap(page);
7643 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7644 flush_dcache_page(page);
7645 kunmap(page);
7646 }
7647 ClearPageChecked(page);
7648 set_page_dirty(page);
7649 SetPageUptodate(page);
7650
7651 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7652 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7653 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7654
7655 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7656
7657 out_unlock:
7658 if (!ret) {
7659 sb_end_pagefault(inode->i_sb);
7660 return VM_FAULT_LOCKED;
7661 }
7662 unlock_page(page);
7663 out:
7664 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7665 out_noreserve:
7666 sb_end_pagefault(inode->i_sb);
7667 return ret;
7668 }
7669
7670 static int btrfs_truncate(struct inode *inode)
7671 {
7672 struct btrfs_root *root = BTRFS_I(inode)->root;
7673 struct btrfs_block_rsv *rsv;
7674 int ret;
7675 int err = 0;
7676 struct btrfs_trans_handle *trans;
7677 u64 mask = root->sectorsize - 1;
7678 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7679
7680 ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
7681 if (ret)
7682 return ret;
7683
7684 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
7685 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
7686
7687 /*
7688 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7689 * 3 things going on here
7690 *
7691 * 1) We need to reserve space for our orphan item and the space to
7692 * delete our orphan item. Lord knows we don't want to have a dangling
7693 * orphan item because we didn't reserve space to remove it.
7694 *
7695 * 2) We need to reserve space to update our inode.
7696 *
7697 * 3) We need to have something to cache all the space that is going to
7698 * be free'd up by the truncate operation, but also have some slack
7699 * space reserved in case it uses space during the truncate (thank you
7700 * very much snapshotting).
7701 *
7702 * And we need these to all be seperate. The fact is we can use alot of
7703 * space doing the truncate, and we have no earthly idea how much space
7704 * we will use, so we need the truncate reservation to be seperate so it
7705 * doesn't end up using space reserved for updating the inode or
7706 * removing the orphan item. We also need to be able to stop the
7707 * transaction and start a new one, which means we need to be able to
7708 * update the inode several times, and we have no idea of knowing how
7709 * many times that will be, so we can't just reserve 1 item for the
7710 * entirety of the opration, so that has to be done seperately as well.
7711 * Then there is the orphan item, which does indeed need to be held on
7712 * to for the whole operation, and we need nobody to touch this reserved
7713 * space except the orphan code.
7714 *
7715 * So that leaves us with
7716 *
7717 * 1) root->orphan_block_rsv - for the orphan deletion.
7718 * 2) rsv - for the truncate reservation, which we will steal from the
7719 * transaction reservation.
7720 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7721 * updating the inode.
7722 */
7723 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7724 if (!rsv)
7725 return -ENOMEM;
7726 rsv->size = min_size;
7727 rsv->failfast = 1;
7728
7729 /*
7730 * 1 for the truncate slack space
7731 * 1 for updating the inode.
7732 */
7733 trans = btrfs_start_transaction(root, 2);
7734 if (IS_ERR(trans)) {
7735 err = PTR_ERR(trans);
7736 goto out;
7737 }
7738
7739 /* Migrate the slack space for the truncate to our reserve */
7740 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7741 min_size);
7742 BUG_ON(ret);
7743
7744 /*
7745 * setattr is responsible for setting the ordered_data_close flag,
7746 * but that is only tested during the last file release. That
7747 * could happen well after the next commit, leaving a great big
7748 * window where new writes may get lost if someone chooses to write
7749 * to this file after truncating to zero
7750 *
7751 * The inode doesn't have any dirty data here, and so if we commit
7752 * this is a noop. If someone immediately starts writing to the inode
7753 * it is very likely we'll catch some of their writes in this
7754 * transaction, and the commit will find this file on the ordered
7755 * data list with good things to send down.
7756 *
7757 * This is a best effort solution, there is still a window where
7758 * using truncate to replace the contents of the file will
7759 * end up with a zero length file after a crash.
7760 */
7761 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7762 &BTRFS_I(inode)->runtime_flags))
7763 btrfs_add_ordered_operation(trans, root, inode);
7764
7765 /*
7766 * So if we truncate and then write and fsync we normally would just
7767 * write the extents that changed, which is a problem if we need to
7768 * first truncate that entire inode. So set this flag so we write out
7769 * all of the extents in the inode to the sync log so we're completely
7770 * safe.
7771 */
7772 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7773 trans->block_rsv = rsv;
7774
7775 while (1) {
7776 ret = btrfs_truncate_inode_items(trans, root, inode,
7777 inode->i_size,
7778 BTRFS_EXTENT_DATA_KEY);
7779 if (ret != -ENOSPC) {
7780 err = ret;
7781 break;
7782 }
7783
7784 trans->block_rsv = &root->fs_info->trans_block_rsv;
7785 ret = btrfs_update_inode(trans, root, inode);
7786 if (ret) {
7787 err = ret;
7788 break;
7789 }
7790
7791 btrfs_end_transaction(trans, root);
7792 btrfs_btree_balance_dirty(root);
7793
7794 trans = btrfs_start_transaction(root, 2);
7795 if (IS_ERR(trans)) {
7796 ret = err = PTR_ERR(trans);
7797 trans = NULL;
7798 break;
7799 }
7800
7801 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7802 rsv, min_size);
7803 BUG_ON(ret); /* shouldn't happen */
7804 trans->block_rsv = rsv;
7805 }
7806
7807 if (ret == 0 && inode->i_nlink > 0) {
7808 trans->block_rsv = root->orphan_block_rsv;
7809 ret = btrfs_orphan_del(trans, inode);
7810 if (ret)
7811 err = ret;
7812 }
7813
7814 if (trans) {
7815 trans->block_rsv = &root->fs_info->trans_block_rsv;
7816 ret = btrfs_update_inode(trans, root, inode);
7817 if (ret && !err)
7818 err = ret;
7819
7820 ret = btrfs_end_transaction(trans, root);
7821 btrfs_btree_balance_dirty(root);
7822 }
7823
7824 out:
7825 btrfs_free_block_rsv(root, rsv);
7826
7827 if (ret && !err)
7828 err = ret;
7829
7830 return err;
7831 }
7832
7833 /*
7834 * create a new subvolume directory/inode (helper for the ioctl).
7835 */
7836 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7837 struct btrfs_root *new_root, u64 new_dirid)
7838 {
7839 struct inode *inode;
7840 int err;
7841 u64 index = 0;
7842
7843 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7844 new_dirid, new_dirid,
7845 S_IFDIR | (~current_umask() & S_IRWXUGO),
7846 &index);
7847 if (IS_ERR(inode))
7848 return PTR_ERR(inode);
7849 inode->i_op = &btrfs_dir_inode_operations;
7850 inode->i_fop = &btrfs_dir_file_operations;
7851
7852 set_nlink(inode, 1);
7853 btrfs_i_size_write(inode, 0);
7854
7855 err = btrfs_update_inode(trans, new_root, inode);
7856
7857 iput(inode);
7858 return err;
7859 }
7860
7861 struct inode *btrfs_alloc_inode(struct super_block *sb)
7862 {
7863 struct btrfs_inode *ei;
7864 struct inode *inode;
7865
7866 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7867 if (!ei)
7868 return NULL;
7869
7870 ei->root = NULL;
7871 ei->generation = 0;
7872 ei->last_trans = 0;
7873 ei->last_sub_trans = 0;
7874 ei->logged_trans = 0;
7875 ei->delalloc_bytes = 0;
7876 ei->disk_i_size = 0;
7877 ei->flags = 0;
7878 ei->csum_bytes = 0;
7879 ei->index_cnt = (u64)-1;
7880 ei->last_unlink_trans = 0;
7881 ei->last_log_commit = 0;
7882
7883 spin_lock_init(&ei->lock);
7884 ei->outstanding_extents = 0;
7885 ei->reserved_extents = 0;
7886
7887 ei->runtime_flags = 0;
7888 ei->force_compress = BTRFS_COMPRESS_NONE;
7889
7890 ei->delayed_node = NULL;
7891
7892 inode = &ei->vfs_inode;
7893 extent_map_tree_init(&ei->extent_tree);
7894 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7895 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7896 ei->io_tree.track_uptodate = 1;
7897 ei->io_failure_tree.track_uptodate = 1;
7898 atomic_set(&ei->sync_writers, 0);
7899 mutex_init(&ei->log_mutex);
7900 mutex_init(&ei->delalloc_mutex);
7901 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7902 INIT_LIST_HEAD(&ei->delalloc_inodes);
7903 INIT_LIST_HEAD(&ei->ordered_operations);
7904 RB_CLEAR_NODE(&ei->rb_node);
7905
7906 return inode;
7907 }
7908
7909 static void btrfs_i_callback(struct rcu_head *head)
7910 {
7911 struct inode *inode = container_of(head, struct inode, i_rcu);
7912 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7913 }
7914
7915 void btrfs_destroy_inode(struct inode *inode)
7916 {
7917 struct btrfs_ordered_extent *ordered;
7918 struct btrfs_root *root = BTRFS_I(inode)->root;
7919
7920 WARN_ON(!hlist_empty(&inode->i_dentry));
7921 WARN_ON(inode->i_data.nrpages);
7922 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7923 WARN_ON(BTRFS_I(inode)->reserved_extents);
7924 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7925 WARN_ON(BTRFS_I(inode)->csum_bytes);
7926
7927 /*
7928 * This can happen where we create an inode, but somebody else also
7929 * created the same inode and we need to destroy the one we already
7930 * created.
7931 */
7932 if (!root)
7933 goto free;
7934
7935 /*
7936 * Make sure we're properly removed from the ordered operation
7937 * lists.
7938 */
7939 smp_mb();
7940 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7941 spin_lock(&root->fs_info->ordered_extent_lock);
7942 list_del_init(&BTRFS_I(inode)->ordered_operations);
7943 spin_unlock(&root->fs_info->ordered_extent_lock);
7944 }
7945
7946 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7947 &BTRFS_I(inode)->runtime_flags)) {
7948 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
7949 (unsigned long long)btrfs_ino(inode));
7950 atomic_dec(&root->orphan_inodes);
7951 }
7952
7953 while (1) {
7954 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7955 if (!ordered)
7956 break;
7957 else {
7958 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
7959 (unsigned long long)ordered->file_offset,
7960 (unsigned long long)ordered->len);
7961 btrfs_remove_ordered_extent(inode, ordered);
7962 btrfs_put_ordered_extent(ordered);
7963 btrfs_put_ordered_extent(ordered);
7964 }
7965 }
7966 inode_tree_del(inode);
7967 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7968 free:
7969 btrfs_remove_delayed_node(inode);
7970 call_rcu(&inode->i_rcu, btrfs_i_callback);
7971 }
7972
7973 int btrfs_drop_inode(struct inode *inode)
7974 {
7975 struct btrfs_root *root = BTRFS_I(inode)->root;
7976
7977 /* the snap/subvol tree is on deleting */
7978 if (btrfs_root_refs(&root->root_item) == 0 &&
7979 root != root->fs_info->tree_root)
7980 return 1;
7981 else
7982 return generic_drop_inode(inode);
7983 }
7984
7985 static void init_once(void *foo)
7986 {
7987 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7988
7989 inode_init_once(&ei->vfs_inode);
7990 }
7991
7992 void btrfs_destroy_cachep(void)
7993 {
7994 /*
7995 * Make sure all delayed rcu free inodes are flushed before we
7996 * destroy cache.
7997 */
7998 rcu_barrier();
7999 if (btrfs_inode_cachep)
8000 kmem_cache_destroy(btrfs_inode_cachep);
8001 if (btrfs_trans_handle_cachep)
8002 kmem_cache_destroy(btrfs_trans_handle_cachep);
8003 if (btrfs_transaction_cachep)
8004 kmem_cache_destroy(btrfs_transaction_cachep);
8005 if (btrfs_path_cachep)
8006 kmem_cache_destroy(btrfs_path_cachep);
8007 if (btrfs_free_space_cachep)
8008 kmem_cache_destroy(btrfs_free_space_cachep);
8009 if (btrfs_delalloc_work_cachep)
8010 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8011 }
8012
8013 int btrfs_init_cachep(void)
8014 {
8015 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8016 sizeof(struct btrfs_inode), 0,
8017 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8018 if (!btrfs_inode_cachep)
8019 goto fail;
8020
8021 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8022 sizeof(struct btrfs_trans_handle), 0,
8023 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8024 if (!btrfs_trans_handle_cachep)
8025 goto fail;
8026
8027 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8028 sizeof(struct btrfs_transaction), 0,
8029 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8030 if (!btrfs_transaction_cachep)
8031 goto fail;
8032
8033 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8034 sizeof(struct btrfs_path), 0,
8035 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8036 if (!btrfs_path_cachep)
8037 goto fail;
8038
8039 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8040 sizeof(struct btrfs_free_space), 0,
8041 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8042 if (!btrfs_free_space_cachep)
8043 goto fail;
8044
8045 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8046 sizeof(struct btrfs_delalloc_work), 0,
8047 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8048 NULL);
8049 if (!btrfs_delalloc_work_cachep)
8050 goto fail;
8051
8052 return 0;
8053 fail:
8054 btrfs_destroy_cachep();
8055 return -ENOMEM;
8056 }
8057
8058 static int btrfs_getattr(struct vfsmount *mnt,
8059 struct dentry *dentry, struct kstat *stat)
8060 {
8061 u64 delalloc_bytes;
8062 struct inode *inode = dentry->d_inode;
8063 u32 blocksize = inode->i_sb->s_blocksize;
8064
8065 generic_fillattr(inode, stat);
8066 stat->dev = BTRFS_I(inode)->root->anon_dev;
8067 stat->blksize = PAGE_CACHE_SIZE;
8068
8069 spin_lock(&BTRFS_I(inode)->lock);
8070 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8071 spin_unlock(&BTRFS_I(inode)->lock);
8072 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8073 ALIGN(delalloc_bytes, blocksize)) >> 9;
8074 return 0;
8075 }
8076
8077 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8078 struct inode *new_dir, struct dentry *new_dentry)
8079 {
8080 struct btrfs_trans_handle *trans;
8081 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8082 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8083 struct inode *new_inode = new_dentry->d_inode;
8084 struct inode *old_inode = old_dentry->d_inode;
8085 struct timespec ctime = CURRENT_TIME;
8086 u64 index = 0;
8087 u64 root_objectid;
8088 int ret;
8089 u64 old_ino = btrfs_ino(old_inode);
8090
8091 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8092 return -EPERM;
8093
8094 /* we only allow rename subvolume link between subvolumes */
8095 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8096 return -EXDEV;
8097
8098 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8099 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8100 return -ENOTEMPTY;
8101
8102 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8103 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8104 return -ENOTEMPTY;
8105
8106
8107 /* check for collisions, even if the name isn't there */
8108 ret = btrfs_check_dir_item_collision(root, new_dir->i_ino,
8109 new_dentry->d_name.name,
8110 new_dentry->d_name.len);
8111
8112 if (ret) {
8113 if (ret == -EEXIST) {
8114 /* we shouldn't get
8115 * eexist without a new_inode */
8116 if (!new_inode) {
8117 WARN_ON(1);
8118 return ret;
8119 }
8120 } else {
8121 /* maybe -EOVERFLOW */
8122 return ret;
8123 }
8124 }
8125 ret = 0;
8126
8127 /*
8128 * we're using rename to replace one file with another.
8129 * and the replacement file is large. Start IO on it now so
8130 * we don't add too much work to the end of the transaction
8131 */
8132 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8133 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8134 filemap_flush(old_inode->i_mapping);
8135
8136 /* close the racy window with snapshot create/destroy ioctl */
8137 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8138 down_read(&root->fs_info->subvol_sem);
8139 /*
8140 * We want to reserve the absolute worst case amount of items. So if
8141 * both inodes are subvols and we need to unlink them then that would
8142 * require 4 item modifications, but if they are both normal inodes it
8143 * would require 5 item modifications, so we'll assume their normal
8144 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8145 * should cover the worst case number of items we'll modify.
8146 */
8147 trans = btrfs_start_transaction(root, 11);
8148 if (IS_ERR(trans)) {
8149 ret = PTR_ERR(trans);
8150 goto out_notrans;
8151 }
8152
8153 if (dest != root)
8154 btrfs_record_root_in_trans(trans, dest);
8155
8156 ret = btrfs_set_inode_index(new_dir, &index);
8157 if (ret)
8158 goto out_fail;
8159
8160 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8161 /* force full log commit if subvolume involved. */
8162 root->fs_info->last_trans_log_full_commit = trans->transid;
8163 } else {
8164 ret = btrfs_insert_inode_ref(trans, dest,
8165 new_dentry->d_name.name,
8166 new_dentry->d_name.len,
8167 old_ino,
8168 btrfs_ino(new_dir), index);
8169 if (ret)
8170 goto out_fail;
8171 /*
8172 * this is an ugly little race, but the rename is required
8173 * to make sure that if we crash, the inode is either at the
8174 * old name or the new one. pinning the log transaction lets
8175 * us make sure we don't allow a log commit to come in after
8176 * we unlink the name but before we add the new name back in.
8177 */
8178 btrfs_pin_log_trans(root);
8179 }
8180 /*
8181 * make sure the inode gets flushed if it is replacing
8182 * something.
8183 */
8184 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8185 btrfs_add_ordered_operation(trans, root, old_inode);
8186
8187 inode_inc_iversion(old_dir);
8188 inode_inc_iversion(new_dir);
8189 inode_inc_iversion(old_inode);
8190 old_dir->i_ctime = old_dir->i_mtime = ctime;
8191 new_dir->i_ctime = new_dir->i_mtime = ctime;
8192 old_inode->i_ctime = ctime;
8193
8194 if (old_dentry->d_parent != new_dentry->d_parent)
8195 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8196
8197 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8198 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8199 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8200 old_dentry->d_name.name,
8201 old_dentry->d_name.len);
8202 } else {
8203 ret = __btrfs_unlink_inode(trans, root, old_dir,
8204 old_dentry->d_inode,
8205 old_dentry->d_name.name,
8206 old_dentry->d_name.len);
8207 if (!ret)
8208 ret = btrfs_update_inode(trans, root, old_inode);
8209 }
8210 if (ret) {
8211 btrfs_abort_transaction(trans, root, ret);
8212 goto out_fail;
8213 }
8214
8215 if (new_inode) {
8216 inode_inc_iversion(new_inode);
8217 new_inode->i_ctime = CURRENT_TIME;
8218 if (unlikely(btrfs_ino(new_inode) ==
8219 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8220 root_objectid = BTRFS_I(new_inode)->location.objectid;
8221 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8222 root_objectid,
8223 new_dentry->d_name.name,
8224 new_dentry->d_name.len);
8225 BUG_ON(new_inode->i_nlink == 0);
8226 } else {
8227 ret = btrfs_unlink_inode(trans, dest, new_dir,
8228 new_dentry->d_inode,
8229 new_dentry->d_name.name,
8230 new_dentry->d_name.len);
8231 }
8232 if (!ret && new_inode->i_nlink == 0) {
8233 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8234 BUG_ON(ret);
8235 }
8236 if (ret) {
8237 btrfs_abort_transaction(trans, root, ret);
8238 goto out_fail;
8239 }
8240 }
8241
8242 ret = btrfs_add_link(trans, new_dir, old_inode,
8243 new_dentry->d_name.name,
8244 new_dentry->d_name.len, 0, index);
8245 if (ret) {
8246 btrfs_abort_transaction(trans, root, ret);
8247 goto out_fail;
8248 }
8249
8250 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8251 struct dentry *parent = new_dentry->d_parent;
8252 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8253 btrfs_end_log_trans(root);
8254 }
8255 out_fail:
8256 btrfs_end_transaction(trans, root);
8257 out_notrans:
8258 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8259 up_read(&root->fs_info->subvol_sem);
8260
8261 return ret;
8262 }
8263
8264 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8265 {
8266 struct btrfs_delalloc_work *delalloc_work;
8267
8268 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8269 work);
8270 if (delalloc_work->wait)
8271 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
8272 else
8273 filemap_flush(delalloc_work->inode->i_mapping);
8274
8275 if (delalloc_work->delay_iput)
8276 btrfs_add_delayed_iput(delalloc_work->inode);
8277 else
8278 iput(delalloc_work->inode);
8279 complete(&delalloc_work->completion);
8280 }
8281
8282 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8283 int wait, int delay_iput)
8284 {
8285 struct btrfs_delalloc_work *work;
8286
8287 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8288 if (!work)
8289 return NULL;
8290
8291 init_completion(&work->completion);
8292 INIT_LIST_HEAD(&work->list);
8293 work->inode = inode;
8294 work->wait = wait;
8295 work->delay_iput = delay_iput;
8296 work->work.func = btrfs_run_delalloc_work;
8297
8298 return work;
8299 }
8300
8301 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8302 {
8303 wait_for_completion(&work->completion);
8304 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8305 }
8306
8307 /*
8308 * some fairly slow code that needs optimization. This walks the list
8309 * of all the inodes with pending delalloc and forces them to disk.
8310 */
8311 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8312 {
8313 struct btrfs_inode *binode;
8314 struct inode *inode;
8315 struct btrfs_delalloc_work *work, *next;
8316 struct list_head works;
8317 struct list_head splice;
8318 int ret = 0;
8319
8320 if (root->fs_info->sb->s_flags & MS_RDONLY)
8321 return -EROFS;
8322
8323 INIT_LIST_HEAD(&works);
8324 INIT_LIST_HEAD(&splice);
8325
8326 spin_lock(&root->fs_info->delalloc_lock);
8327 list_splice_init(&root->fs_info->delalloc_inodes, &splice);
8328 while (!list_empty(&splice)) {
8329 binode = list_entry(splice.next, struct btrfs_inode,
8330 delalloc_inodes);
8331
8332 list_del_init(&binode->delalloc_inodes);
8333
8334 inode = igrab(&binode->vfs_inode);
8335 if (!inode) {
8336 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
8337 &binode->runtime_flags);
8338 continue;
8339 }
8340
8341 list_add_tail(&binode->delalloc_inodes,
8342 &root->fs_info->delalloc_inodes);
8343 spin_unlock(&root->fs_info->delalloc_lock);
8344
8345 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8346 if (unlikely(!work)) {
8347 ret = -ENOMEM;
8348 goto out;
8349 }
8350 list_add_tail(&work->list, &works);
8351 btrfs_queue_worker(&root->fs_info->flush_workers,
8352 &work->work);
8353
8354 cond_resched();
8355 spin_lock(&root->fs_info->delalloc_lock);
8356 }
8357 spin_unlock(&root->fs_info->delalloc_lock);
8358
8359 list_for_each_entry_safe(work, next, &works, list) {
8360 list_del_init(&work->list);
8361 btrfs_wait_and_free_delalloc_work(work);
8362 }
8363
8364 /* the filemap_flush will queue IO into the worker threads, but
8365 * we have to make sure the IO is actually started and that
8366 * ordered extents get created before we return
8367 */
8368 atomic_inc(&root->fs_info->async_submit_draining);
8369 while (atomic_read(&root->fs_info->nr_async_submits) ||
8370 atomic_read(&root->fs_info->async_delalloc_pages)) {
8371 wait_event(root->fs_info->async_submit_wait,
8372 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8373 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8374 }
8375 atomic_dec(&root->fs_info->async_submit_draining);
8376 return 0;
8377 out:
8378 list_for_each_entry_safe(work, next, &works, list) {
8379 list_del_init(&work->list);
8380 btrfs_wait_and_free_delalloc_work(work);
8381 }
8382
8383 if (!list_empty_careful(&splice)) {
8384 spin_lock(&root->fs_info->delalloc_lock);
8385 list_splice_tail(&splice, &root->fs_info->delalloc_inodes);
8386 spin_unlock(&root->fs_info->delalloc_lock);
8387 }
8388 return ret;
8389 }
8390
8391 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8392 const char *symname)
8393 {
8394 struct btrfs_trans_handle *trans;
8395 struct btrfs_root *root = BTRFS_I(dir)->root;
8396 struct btrfs_path *path;
8397 struct btrfs_key key;
8398 struct inode *inode = NULL;
8399 int err;
8400 int drop_inode = 0;
8401 u64 objectid;
8402 u64 index = 0 ;
8403 int name_len;
8404 int datasize;
8405 unsigned long ptr;
8406 struct btrfs_file_extent_item *ei;
8407 struct extent_buffer *leaf;
8408
8409 name_len = strlen(symname) + 1;
8410 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8411 return -ENAMETOOLONG;
8412
8413 /*
8414 * 2 items for inode item and ref
8415 * 2 items for dir items
8416 * 1 item for xattr if selinux is on
8417 */
8418 trans = btrfs_start_transaction(root, 5);
8419 if (IS_ERR(trans))
8420 return PTR_ERR(trans);
8421
8422 err = btrfs_find_free_ino(root, &objectid);
8423 if (err)
8424 goto out_unlock;
8425
8426 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8427 dentry->d_name.len, btrfs_ino(dir), objectid,
8428 S_IFLNK|S_IRWXUGO, &index);
8429 if (IS_ERR(inode)) {
8430 err = PTR_ERR(inode);
8431 goto out_unlock;
8432 }
8433
8434 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8435 if (err) {
8436 drop_inode = 1;
8437 goto out_unlock;
8438 }
8439
8440 /*
8441 * If the active LSM wants to access the inode during
8442 * d_instantiate it needs these. Smack checks to see
8443 * if the filesystem supports xattrs by looking at the
8444 * ops vector.
8445 */
8446 inode->i_fop = &btrfs_file_operations;
8447 inode->i_op = &btrfs_file_inode_operations;
8448
8449 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8450 if (err)
8451 drop_inode = 1;
8452 else {
8453 inode->i_mapping->a_ops = &btrfs_aops;
8454 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8455 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8456 }
8457 if (drop_inode)
8458 goto out_unlock;
8459
8460 path = btrfs_alloc_path();
8461 if (!path) {
8462 err = -ENOMEM;
8463 drop_inode = 1;
8464 goto out_unlock;
8465 }
8466 key.objectid = btrfs_ino(inode);
8467 key.offset = 0;
8468 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8469 datasize = btrfs_file_extent_calc_inline_size(name_len);
8470 err = btrfs_insert_empty_item(trans, root, path, &key,
8471 datasize);
8472 if (err) {
8473 drop_inode = 1;
8474 btrfs_free_path(path);
8475 goto out_unlock;
8476 }
8477 leaf = path->nodes[0];
8478 ei = btrfs_item_ptr(leaf, path->slots[0],
8479 struct btrfs_file_extent_item);
8480 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8481 btrfs_set_file_extent_type(leaf, ei,
8482 BTRFS_FILE_EXTENT_INLINE);
8483 btrfs_set_file_extent_encryption(leaf, ei, 0);
8484 btrfs_set_file_extent_compression(leaf, ei, 0);
8485 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8486 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8487
8488 ptr = btrfs_file_extent_inline_start(ei);
8489 write_extent_buffer(leaf, symname, ptr, name_len);
8490 btrfs_mark_buffer_dirty(leaf);
8491 btrfs_free_path(path);
8492
8493 inode->i_op = &btrfs_symlink_inode_operations;
8494 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8495 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8496 inode_set_bytes(inode, name_len);
8497 btrfs_i_size_write(inode, name_len - 1);
8498 err = btrfs_update_inode(trans, root, inode);
8499 if (err)
8500 drop_inode = 1;
8501
8502 out_unlock:
8503 if (!err)
8504 d_instantiate(dentry, inode);
8505 btrfs_end_transaction(trans, root);
8506 if (drop_inode) {
8507 inode_dec_link_count(inode);
8508 iput(inode);
8509 }
8510 btrfs_btree_balance_dirty(root);
8511 return err;
8512 }
8513
8514 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8515 u64 start, u64 num_bytes, u64 min_size,
8516 loff_t actual_len, u64 *alloc_hint,
8517 struct btrfs_trans_handle *trans)
8518 {
8519 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8520 struct extent_map *em;
8521 struct btrfs_root *root = BTRFS_I(inode)->root;
8522 struct btrfs_key ins;
8523 u64 cur_offset = start;
8524 u64 i_size;
8525 u64 cur_bytes;
8526 int ret = 0;
8527 bool own_trans = true;
8528
8529 if (trans)
8530 own_trans = false;
8531 while (num_bytes > 0) {
8532 if (own_trans) {
8533 trans = btrfs_start_transaction(root, 3);
8534 if (IS_ERR(trans)) {
8535 ret = PTR_ERR(trans);
8536 break;
8537 }
8538 }
8539
8540 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8541 cur_bytes = max(cur_bytes, min_size);
8542 ret = btrfs_reserve_extent(trans, root, cur_bytes,
8543 min_size, 0, *alloc_hint, &ins, 1);
8544 if (ret) {
8545 if (own_trans)
8546 btrfs_end_transaction(trans, root);
8547 break;
8548 }
8549
8550 ret = insert_reserved_file_extent(trans, inode,
8551 cur_offset, ins.objectid,
8552 ins.offset, ins.offset,
8553 ins.offset, 0, 0, 0,
8554 BTRFS_FILE_EXTENT_PREALLOC);
8555 if (ret) {
8556 btrfs_abort_transaction(trans, root, ret);
8557 if (own_trans)
8558 btrfs_end_transaction(trans, root);
8559 break;
8560 }
8561 btrfs_drop_extent_cache(inode, cur_offset,
8562 cur_offset + ins.offset -1, 0);
8563
8564 em = alloc_extent_map();
8565 if (!em) {
8566 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8567 &BTRFS_I(inode)->runtime_flags);
8568 goto next;
8569 }
8570
8571 em->start = cur_offset;
8572 em->orig_start = cur_offset;
8573 em->len = ins.offset;
8574 em->block_start = ins.objectid;
8575 em->block_len = ins.offset;
8576 em->orig_block_len = ins.offset;
8577 em->bdev = root->fs_info->fs_devices->latest_bdev;
8578 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8579 em->generation = trans->transid;
8580
8581 while (1) {
8582 write_lock(&em_tree->lock);
8583 ret = add_extent_mapping(em_tree, em);
8584 if (!ret)
8585 list_move(&em->list,
8586 &em_tree->modified_extents);
8587 write_unlock(&em_tree->lock);
8588 if (ret != -EEXIST)
8589 break;
8590 btrfs_drop_extent_cache(inode, cur_offset,
8591 cur_offset + ins.offset - 1,
8592 0);
8593 }
8594 free_extent_map(em);
8595 next:
8596 num_bytes -= ins.offset;
8597 cur_offset += ins.offset;
8598 *alloc_hint = ins.objectid + ins.offset;
8599
8600 inode_inc_iversion(inode);
8601 inode->i_ctime = CURRENT_TIME;
8602 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8603 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8604 (actual_len > inode->i_size) &&
8605 (cur_offset > inode->i_size)) {
8606 if (cur_offset > actual_len)
8607 i_size = actual_len;
8608 else
8609 i_size = cur_offset;
8610 i_size_write(inode, i_size);
8611 btrfs_ordered_update_i_size(inode, i_size, NULL);
8612 }
8613
8614 ret = btrfs_update_inode(trans, root, inode);
8615
8616 if (ret) {
8617 btrfs_abort_transaction(trans, root, ret);
8618 if (own_trans)
8619 btrfs_end_transaction(trans, root);
8620 break;
8621 }
8622
8623 if (own_trans)
8624 btrfs_end_transaction(trans, root);
8625 }
8626 return ret;
8627 }
8628
8629 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8630 u64 start, u64 num_bytes, u64 min_size,
8631 loff_t actual_len, u64 *alloc_hint)
8632 {
8633 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8634 min_size, actual_len, alloc_hint,
8635 NULL);
8636 }
8637
8638 int btrfs_prealloc_file_range_trans(struct inode *inode,
8639 struct btrfs_trans_handle *trans, int mode,
8640 u64 start, u64 num_bytes, u64 min_size,
8641 loff_t actual_len, u64 *alloc_hint)
8642 {
8643 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8644 min_size, actual_len, alloc_hint, trans);
8645 }
8646
8647 static int btrfs_set_page_dirty(struct page *page)
8648 {
8649 return __set_page_dirty_nobuffers(page);
8650 }
8651
8652 static int btrfs_permission(struct inode *inode, int mask)
8653 {
8654 struct btrfs_root *root = BTRFS_I(inode)->root;
8655 umode_t mode = inode->i_mode;
8656
8657 if (mask & MAY_WRITE &&
8658 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8659 if (btrfs_root_readonly(root))
8660 return -EROFS;
8661 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8662 return -EACCES;
8663 }
8664 return generic_permission(inode, mask);
8665 }
8666
8667 static const struct inode_operations btrfs_dir_inode_operations = {
8668 .getattr = btrfs_getattr,
8669 .lookup = btrfs_lookup,
8670 .create = btrfs_create,
8671 .unlink = btrfs_unlink,
8672 .link = btrfs_link,
8673 .mkdir = btrfs_mkdir,
8674 .rmdir = btrfs_rmdir,
8675 .rename = btrfs_rename,
8676 .symlink = btrfs_symlink,
8677 .setattr = btrfs_setattr,
8678 .mknod = btrfs_mknod,
8679 .setxattr = btrfs_setxattr,
8680 .getxattr = btrfs_getxattr,
8681 .listxattr = btrfs_listxattr,
8682 .removexattr = btrfs_removexattr,
8683 .permission = btrfs_permission,
8684 .get_acl = btrfs_get_acl,
8685 };
8686 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8687 .lookup = btrfs_lookup,
8688 .permission = btrfs_permission,
8689 .get_acl = btrfs_get_acl,
8690 };
8691
8692 static const struct file_operations btrfs_dir_file_operations = {
8693 .llseek = generic_file_llseek,
8694 .read = generic_read_dir,
8695 .readdir = btrfs_real_readdir,
8696 .unlocked_ioctl = btrfs_ioctl,
8697 #ifdef CONFIG_COMPAT
8698 .compat_ioctl = btrfs_ioctl,
8699 #endif
8700 .release = btrfs_release_file,
8701 .fsync = btrfs_sync_file,
8702 };
8703
8704 static struct extent_io_ops btrfs_extent_io_ops = {
8705 .fill_delalloc = run_delalloc_range,
8706 .submit_bio_hook = btrfs_submit_bio_hook,
8707 .merge_bio_hook = btrfs_merge_bio_hook,
8708 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8709 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8710 .writepage_start_hook = btrfs_writepage_start_hook,
8711 .set_bit_hook = btrfs_set_bit_hook,
8712 .clear_bit_hook = btrfs_clear_bit_hook,
8713 .merge_extent_hook = btrfs_merge_extent_hook,
8714 .split_extent_hook = btrfs_split_extent_hook,
8715 };
8716
8717 /*
8718 * btrfs doesn't support the bmap operation because swapfiles
8719 * use bmap to make a mapping of extents in the file. They assume
8720 * these extents won't change over the life of the file and they
8721 * use the bmap result to do IO directly to the drive.
8722 *
8723 * the btrfs bmap call would return logical addresses that aren't
8724 * suitable for IO and they also will change frequently as COW
8725 * operations happen. So, swapfile + btrfs == corruption.
8726 *
8727 * For now we're avoiding this by dropping bmap.
8728 */
8729 static const struct address_space_operations btrfs_aops = {
8730 .readpage = btrfs_readpage,
8731 .writepage = btrfs_writepage,
8732 .writepages = btrfs_writepages,
8733 .readpages = btrfs_readpages,
8734 .direct_IO = btrfs_direct_IO,
8735 .invalidatepage = btrfs_invalidatepage,
8736 .releasepage = btrfs_releasepage,
8737 .set_page_dirty = btrfs_set_page_dirty,
8738 .error_remove_page = generic_error_remove_page,
8739 };
8740
8741 static const struct address_space_operations btrfs_symlink_aops = {
8742 .readpage = btrfs_readpage,
8743 .writepage = btrfs_writepage,
8744 .invalidatepage = btrfs_invalidatepage,
8745 .releasepage = btrfs_releasepage,
8746 };
8747
8748 static const struct inode_operations btrfs_file_inode_operations = {
8749 .getattr = btrfs_getattr,
8750 .setattr = btrfs_setattr,
8751 .setxattr = btrfs_setxattr,
8752 .getxattr = btrfs_getxattr,
8753 .listxattr = btrfs_listxattr,
8754 .removexattr = btrfs_removexattr,
8755 .permission = btrfs_permission,
8756 .fiemap = btrfs_fiemap,
8757 .get_acl = btrfs_get_acl,
8758 .update_time = btrfs_update_time,
8759 };
8760 static const struct inode_operations btrfs_special_inode_operations = {
8761 .getattr = btrfs_getattr,
8762 .setattr = btrfs_setattr,
8763 .permission = btrfs_permission,
8764 .setxattr = btrfs_setxattr,
8765 .getxattr = btrfs_getxattr,
8766 .listxattr = btrfs_listxattr,
8767 .removexattr = btrfs_removexattr,
8768 .get_acl = btrfs_get_acl,
8769 .update_time = btrfs_update_time,
8770 };
8771 static const struct inode_operations btrfs_symlink_inode_operations = {
8772 .readlink = generic_readlink,
8773 .follow_link = page_follow_link_light,
8774 .put_link = page_put_link,
8775 .getattr = btrfs_getattr,
8776 .setattr = btrfs_setattr,
8777 .permission = btrfs_permission,
8778 .setxattr = btrfs_setxattr,
8779 .getxattr = btrfs_getxattr,
8780 .listxattr = btrfs_listxattr,
8781 .removexattr = btrfs_removexattr,
8782 .get_acl = btrfs_get_acl,
8783 .update_time = btrfs_update_time,
8784 };
8785
8786 const struct dentry_operations btrfs_dentry_operations = {
8787 .d_delete = btrfs_dentry_delete,
8788 .d_release = btrfs_dentry_release,
8789 };