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