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