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