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