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