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