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